How to Auto Generate Name Column with Sequence in Odoo

Anyone who uses Odoo can spot that the Name column of a model like Sale or Invoice is generated automatically. In Odoo, we call it Sequence.

In this post, we will try to create a customer model and allow its name column to be auto-generated.

class MyModel(models.Model):
    _name = 'my.model'
    _description = 'My custom model'

    name = fields.Char(string="Name", readonly=True, select=True, copy=False, default='New')

	@api.model
	def create(self, vals):
	   if vals.get('name', 'New') == 'New':
	       vals['name'] = self.env['ir.sequence'].next_by_code('my.model') or 'New'
	   result = super(MyModel, self).create(vals)
	   return result

In the model above, we inherit create method to override the name field with sequence value.

Next, we need to add the sequence definition to an XML file.

<record id="my_model_sequence" model="ir.sequence">
	<field name="name">My Model Sequence</field>
	<field name="code">my.model</field>
	<field name="active">TRUE</field>
	<field name="prefix">MYMODEL-</field>
	<field name="padding">3</field>
	<field name="number_next">1</field>
	<field name="number_increment">1</field>
</record>

After activation, a record will be created in ir.sequence model.

  • name – Name of the record.
  • code – Your model’s table.
  • active – Determine whether the sequence is active or not.
  • prefix – Prefix of the sequence.
  • padding – Sequence size
  • number_next – Next number that will be used
  • number_increment – The next number of the sequence will be incremented by this.

With the setting above, your new model’s record is named MYMODEL-001, MYMODEL-002, MYMODEL-003, and so on.

Leave a Comment

Your email address will not be published. Required fields are marked *


Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close