Skip to Content
Menu
This question has been flagged
2 Replies
1495 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

name = fields.Char(string="Name ID", copy=False, required=True, readonly=True,
default=lambda self: _('New'))
@api.model
def create(self, vals):

if vals.get('name', _("New")) == _("New"):
vals['name'] = self.env['ir.sequence'].next_by_code('pv.plant.sequence') or _("New")
res = super(PvPlant, self).create(vals)
return res

works with the code above

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
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
Related Posts Replies Views Activity
1
Mar 15
8577
2
Jun 24
614
0
Jan 22
1925
2
Oct 20
6874
2
Aug 20
9688