1
votes

I added the part number field in product template model

partnumber = fields.Char(
        'Part Number', compute='_compute_partnumber',
        inverse='_set_partnumber', store=True)

I write the function like internal reference code

@api.depends('product_variant_ids', 'product_variant_ids.partnumber')
def _compute_partnumber(self):
    unique_variants = self.filtered(lambda template: len(template.product_variant_ids) == 1)
    for template in unique_variants:
        template.partnumber = template.product_variant_ids.partnumber
    for template in (self - unique_variants):
        template.partnumber = ''

@api.one
def _set_partnumber(self):
    if len(self.product_variant_ids) == 1:
        self.product_variant_ids.partnumber = self.partnumber

I successfully added part number in product form.I used above methods for name get(to get part number in product description)

My problem is the part number could not saved in create method. the field only saved in edit mode.

1
are you sure that before create you have len in product_variants?dccdany
@dccdany:Thanks for the comment.I just checks and length of product variants are zero.I finally understand the will not set here.code_explorer

1 Answers

1
votes

As "dccdany" already said in his comment, the creation order is a bit tricky on templates. You can see it in the code. First the template will be created. The partnumber won't be set, because there is no variant existing at that point. After template creation, the variants will be created (one line later) without partnumber, so there will be no partnumber after template creation.

What can you do? Just overwrite product.template create(), like:

@api.model
def create(self, vals):
    template = super(ProductTemplate, self).create(vals)
    if 'partnumber' in vals and len(template.product_varient_ids) == 1:
        template.partnumber = vals.get('partnumber')
    return template