This question has been flagged
2 Replies
147 Views

I am trying to generate a unique id using ir.sequence for my newely created model. Here is my python code

name = fields.Char(string="Name",required=True, default= lambda self: self.env['ir.sequence'].next_by_code('pv.plant.sequence'))

the xml is

record id="sequence_pv_plant" model="ir.sequence">

    field name="name">PV Plant Sequence

    field name="code">pv.plant.sequence

    field name="prefix">PV

    field name="padding">4

/record>

this works completely fine! 

but when i try to make the name field as"readonly" the number being generated is with a step of +2. I have checked my step value in the technical--> sequences and it is 1. 


This occurs only when the readonly = True. 
Any help would be appreciated.   

Avatar
Discard
Author Best Answer

Hi thank you for your reply. I tried it and now the field become empty and no generated values are autopopulated. The issue still persist, but when i make the readonly=False the user can type anything in the field but while saving it saves the correct generated values!! 

I also tried making the name field in xml not readable, still there are no values and the field is empty. Is there a way to autopopulate the generated values at the begening and making the readonly=True after the generated values are being populated?

Avatar
Discard
Best Answer

Hi,

The issue is caused by the sequence generation happening both when the record is initially created and when it's read/displayed due to the readonly property.

To fix this issue, you can remove the default sequence generation from the field definition:

name = fields.Char(string="Name", required=True, readonly=True)

Instead, override the create method of your model to generate the sequence only once when the record is created:

@api.model
def create(self, vals):
vals['name'] = self.env['ir.sequence'].next_by_code('pv.plant.sequence')
return super().create(vals)

Also, make sure that the XML code is also correct:

<record id="sequence_pv_plant" model="ir.sequence">
<field name="name">PV Plant Sequence</field>
<field name="code">pv.plant.sequence</field>
<field name="prefix">PV</field>
<field name="padding">4</field>
</record>


Hope it helps

Avatar
Discard