Ernesto Ruiz
Ernesto Ruiz

Reputation: 820

How to create custom char ID field in Odoo model?

In odoo id special field is allways an auto incremental integer. But for my Odoo app I want that field (id) to be a Char for an specific model. That id will also be use for Many2One relations. How can I do that? I am working with Odoo 14

Upvotes: 1

Views: 509

Answers (1)

Luke
Luke

Reputation: 254

I wouldn't recommend manipulating the id field. Instead, I'd suggest you add another char field and then you can use the _sql_constraints attribute on your model. Let's say, for example, your unique Char field is city, you can use the following example:

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

    city = fields.Char(string='City', related='related.model', readonly=False)

    _sql_constraints = [
        ('check_city_unique', 'UNIQUE(city)', 'The city is not unique')
    ]

_sql_constraints accepts three arguments:

  • A unique name for the argument
  • The constraint. In this example we've used unique, but you can use any sql constraint. I use CHECK a lot in odoo. You can learn more about SQL Constraints here: You can learn more about SQL Constraints here
  • An error message when the constraint fails.

You can also find more about constrains on odoo's developer docs

Good luck!

Upvotes: 2

Related Questions