Skip to Content
Menu
This question has been flagged
1 Reply
3687 Views

Hi All,

I am trying to auto-generate the "Default Code" or "Internal Reference" by using logic as below. What I am experiencing that when multiple users try to create product records, my code generates duplicate codes. Probably, an issue with record locking when creating a code using custom code.

Can someone help ...

My code as below -

@api.model
def get_facode(self):
    last_facode_rec = self.env['product.product'].search([('default_code', 'like', 'FA')], order='default_code DESC', limit=1)
    if not last_facode_rec and len(last_facode_rec) == 0:
    return 'FA000001'

last_facode = last_facode_rec[0].default_code 

if last_facode and last_facode != '':
    new_facode = last_facode[:2] + ("000000" + str(int(last_facode[2:])+1))[-6:]
else:
    new_facode = 'FA000001'

return new_facode

Avatar
Discard
Best Answer

Hi,

You can done it easily by defining a sequence in Odoo, seems you are making it tough/difficult by hard coding everything.

Define a sequence in the code or from UI:

<record id="seq_product_code" model="ir.sequence">
<field name="name">Product Code</field>
<field name="code">product.code</field>
<field name="prefix">FA</field>
<field name="padding">3</field>
<field name="company_id" eval="False"/>
</record>

Then you can override the create method of corresponding model and assign the value to corresponding field.

@api.model
def create(self, vals):
vals['default_code'] = self.env['ir.sequence'].next_by_code('product.code') or _('New')
return super(ClassName, self).create(vals)

Also you can check this module in odoo apps store for free for the same: Product Barcode Generator

For creating new sequence in odoo from code, you can see this: How to Add New Sequence in odoo

Thanks


Avatar
Discard