Execute bulk updates in Odoo using Xmlrpc for multiple rows at once

I need assistance updating multiple records of "sale.order.line" products in Odoo Xmlrpc.

for (let i = 0; i <sell.products.length; i ++) {                
          var inParams = [];
          inParams.push ([value1 [i]]);  //id to update
          inParams.push ({
            'name': sale.products [i] .name,
            'product_uom_qty': sales.products [i] .product_uom_qty,
            'price_unit': sales.products [i] .price_unit,
            'product_id': sales.products [i] .product_id
          });
          var params = [];
          params.push (inParams);
          db.execute_kw ('sale.order.line', 'write', params, function (err, value) {
            if (err) {
              return console.log (err);
            }
            return console.log ('Result2:', value);
          });
        } 

The error message displayed is: raise psycopg2.OperationalError (msg) \ npsycopg2.OperationalError: Unable to use a closed cursor.

This operation is being carried out on Odoo version 12. Thank you for your help.

Answer №1

Appreciation for the assistance jo541

I managed to resolve the issue by updating odoo xmlrpc with odoo. The updated code is functioning perfectly:

`for (let i = 0; i <sale.products.length; i ++) {
     var params = {
               'name': 'Product #' + sale.products[i].product_id,
               'product_uom_qty': sale.products[i].product_uom_qty,
               'price_unit': sale.products[i].price_unit,
               'product_id': sale.products[i].product_id
     }
     odoo2.update ("sale.order.line", sale.products [i].id, params, function (err, value) {
               if (err) {
                 return console.log (err);
               }
               console.log (value);

    

     });
    };`

Answer №2

I encountered a similar issue where my Odoo server couldn't handle concurrent connections.

To resolve the problem, I implemented a mutex/lock to restrict simultaneous access to the API, resulting in smooth operation :-)

Below is some code for your reference :

import * as Odoo from "odoo-xmlrpc";
import AwaitLock from 'await-lock';

var odoo = new Odoo({
    url: "odooserver/xmlrpc/2",
    db: "databasename",
    username: "username",
    password: "password"
});

var lock = new AwaitLock();

const callOdoo = async (model, method, params) => {
  return new Promise(async (resolve, reject) => {
    odoo.connect(async (err) => {
      if (err) reject(new Error(err));
      await lock.acquireAsync();
      odoo.execute_kw(model, method, params, (err, value) => {
        lock.release();
        if (err) {
          reject(new Error(err));
        }
        console.log(value);
        resolve(value);
      });
    });
  });
}

async function getStockFromOdoo() {
  let items = await callOdoo(
    'product.product',
    'search_read',
    [
      [[['x_volume', '>=', '0.1']]],
      {'fields': ['x_beername', 'qty_available', 'x_volume', 'name', 'default_code']}
    ]
  );
  // Do something with items here.
}

async function getCustomers() {
  let items = await callOdoo(
    'res.partner',
    'search_read',
    [
      [[['is_company', '=', true],['customer', '=', true]]],
      {'fields': ['name']}
    ]);
  // Do something with items here
}

async function createSaleOrder(order){
  let orderId = await callOdoo(
    'sale.order',
    'create',
    [[{ partner_id: order.customer.id }]]
  );
  order.orders.forEach(async (line) => {
    await callOdoo(
      'sale.order.line',
      'create',
      [[{'order_id': orderId, 'product_id': line.beer.id, 'product_uom_qty': line.quantity}]]);
  });
  // do something with it here.
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How do I include an icon on the far left of my NavBar menu? I'm having trouble figuring out how to add an icon to the header NavBar

How can I add an icon to the left of my NavBar header? I am struggling with adding an icon on the far left side of my NavBar. The NavBar is a custom class from NavBar.js. I want to include an icon in this bar on the leftmost side. I have already added b ...

Converting various forms of data into arrays using JavaScript

I have a series of forms set up like this: <div class="well"> <form> <span class="remove pull-right"><i class="fa fa-times pointer"></i></span> <div class="form-group" style="margin:0"> ...

unable to fix slideshow glitch after multiple cycles

I've encountered an issue with my custom JavaScript picture scroll. After 3-4 photo changes, the script crashes the page unexpectedly. I'm not sure what is causing this problem! Can someone provide assistance? Below is the code snippet: <di ...

What could be causing issues with my JavaScript AJAX?

I'm in the process of developing a basic chat system that automatically loads new messages as they come in. Initially, I used to fetch all messages from the database. However, I encountered an issue where the scroll bar would constantly jump to the bo ...

Determine the execution time of a Python script

I have developed a series of Python scripts to run as the backend of my application. Users are required to upload a file using the provided webpage, where they can track the progress through a displayed progress bar. The file is broken down into frames, ob ...

Using the updated values from a range slider in JavaScript: A step-by-step guide

In the scenario where a slider has been created and the value is being changed using a mouse, the challenge is how to utilize these values as variables in the global scope. It is important that this variable updates to the new value when the slider is ad ...

What is the solution to fixing the error message "TypeError: Unable to access properties of undefined (reading 'words')"?

I successfully integrated crypto-Js into my application for encrypting and decrypting local storage. Everything is functioning as expected. Issue: : However, upon refreshing the page, it suddenly turns black and an error is displayed in the console: TypeE ...

Steer clear of specifying product type when using AJAX to update cart count in Shopify

I have a unique scenario in my Shopify store where I need to update the cart count using Ajax, but exclude a specific product type called 'mw_product_option'. I found a workaround to exclude this product type from the count on a regular page refr ...

Acquiring the selector value from a tag

To summarize: This snippet of code: for(let i = 0; i <= items.length; i++){ console.log(items[i]) } Produces the following output: <a class="photo ajax2" target="_blank" href="/profile/show/3209135.html" data-first="1" data-next="3206884"> ...

What is the best way to implement a loop using JQuery?

<script> $(function() { $('.slideshow').each(function(index, element) { $(element).crossSlide({ sleep: 2, fade: 1 }, [ { src: 'picture' + (index + 1) + '.jpg' } ]); }); ...

What is the best way to display several markers on a Google Map at once?

I am currently working on a functionality where I retrieve latitude and longitude from a JSON file and display markers on a Google map. However, my issue is that only one marker is appearing on the Google map, while the others are not showing up. Below i ...

AngularJS Directive for Creating Dynamic Menus

I am looking to implement a custom mmenu directive in my Angular application. Currently, I have set it up and utilized link: function(){} within the directive. For more information about the jQuery Plugin, you can visit their webpage here: Below is the c ...

Sending a value to a specialized component

Presently, I am using a custom component called Search. This component is responsible for rendering a dropdown menu with different options based on the data provided. It also includes a None option by default. const Search = (props) => { const { type: ...

Save the modal to a variable and display it when clicked

I am trying to create a modal and display it when a user clicks a button. However, I seem to be facing an issue where nothing happens when the button is clicked and there are no errors in the console. $( '.outlet' ).on('click', functio ...

"Enhance your webpage with a captivating opaque background image using Bootstrap

I'm new to exploring Bootstrap and I am currently experimenting with options for displaying content with a semi-transparent background image. Currently, I am using a "well" but I am open to other suggestions. I have managed to place the image inside t ...

Ways to detect scrolling activity on the v-data-table module?

Are you looking for a way to detect scrolling events on the v-data-table component in Vuetify framework? I am referring to the scenario where the table has a fixed height, causing the table body to scroll. <v-data-table fixed-header :height=400 : ...

Automatically Refresh a Div Element Every 5 Seconds Using jQuery's setInterval() Function

My goal is to refresh the left div every 5 seconds using $.ajax to get JSON data and display 4 random elements in that div. However, even though the left div block refreshes, the content remains the same with the same images always showing. view image desc ...

Is there a way to continually monitor for collisions between webpage elements?

After successfully implementing the algorithm, I am currently struggling with finding a way to continuously check if the element has collided with other elements. For example: When the div with id 'water' collides with the div with id 'ora ...

The combination of Masonry, FlexSlider, and endless scrolling functionality creates a

I am currently using the Masonry layout and implementing infinite scroll functionality through a jQuery plugin. Within this content, I have various FlexSlider slideshows. Unfortunately, when I trigger the infinite scroll feature, the slider does not displa ...

issue with scrolling using the ideal scrollbar

Can someone help me figure out how to integrate the 'perfectScrollbar('update')' function with my Angular.js code? $http.get('demo/json/test.json'). success(function(data, status, headers, config) { $scope.items = d ...