Search code examples
python-3.xodoo-12

one2many field stores only last record when fill


please help me regarding one2many field in odoo12. firstly, sorry for bad grammar.

i am getting products from invoice_line_ids of account.invoice model. but when i store these products in my custom model only last record is stored in one2many field in my class. here is my code.

invoice_report = self.create(vals)
product_dict={}
product_list=[]

for line in ids.invoice_line_ids:
    product_dict.update({
        'product_name':line.product_id.name,
        'qty':line.quantity,
        'unit_price':line.price_unit,
        'tax':line.invoice_line_tax_ids.name or "",
        'subtotal':line.price_subtotal
    })

    product_list.append([(1,invoice_report.id,product_dict)])

for data in product_list:
    invoice_report.write({
        'inv_products':data
    })

inv_products is my one2many field invoice_report is my recently created record. i.e custom.invoice(1,)


Solution

  • According to the x2many values filling, the format you used updates an existing record of id id with the values in values. id should be an id of an inv_products record, not a custom.invoice record.

    You should receive an Odoo server error in case record with id equal to 1 does not exist in the database:

    One of the records you are trying to modify has already been deleted (Document type: custom.report.line).
    
    (Records: (1,), User: 2) 
    

    You declared product_dict outside a for loop and you used update inside, at the end of the loop you will have the values of the last line of invoice_line_ids repeated, You asked the system to update a specific line (with id invoice_report.id) with the same values in each iteration when you called write method.

    To add new records to inv_products, use [(0, 0, values)] format:

    invoice_report = self.create(vals)
    product_list = []
    
    for line in ids.invoice_line_ids:
        product_dict = {
    
        }
    
        product_list.append((0, 0, product_dict))
    
    invoice_report.write({
        'inv_products': product_list
    })