Skip to Content
Meniu
Trebuie să fiți înregistrat pentru a interacționa cu comunitatea.
Această întrebare a fost marcată
2 Răspunsuri
450 Vizualizări

I'm trying to create a model field for months that:

  • Displays month names in a selection dropdown
  • Stores the month as an integer value
  • Ensures the integer is preserved during export/import

Here's my current approach:

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

    month = fields.Selection([
        ('1', 'January'),
        ('2', 'February'),
        ('3', 'March'),
        ('4', 'April'),
        ('5', 'May'),
        ('6', 'June'),
        ('7', 'July'),
        ('8', 'August'),
        ('9', 'September'),
        ('10', 'October'),
        ('11', 'November'),
        ('12', 'December')
    ], string='Month')

    month_int = fields.Integer(
        string='Month Number',
        compute='_compute_month_int',
        store=True
    )

    @api.depends('month')
    def _compute_month_int(self):
        for record in self:
            record.month_int = int(record.month) if record.month else False

Questions:

  1. Is this the correct way to create a month selection field that stores as an integer?
  2. Are there any potential issues with export/import using this method?
  3. Would you recommend any improvements to this approach?

I want to ensure:

  • User-friendly month selection
  • Accurate integer storage
  • Compatibility with exports/imports

Any guidance or best practices would be greatly appreciated!

Imagine profil
Abandonează
Autor Cel mai bun răspuns

According to the changes introduced in  IMP] fields: remove support for non-string selections #29039, the ability to use integers as value in Selection fields has been removed. This means that all selection values must now be strings. 

I absolutely don’t understand why this change was made. Using integers as selection values feels more intuitive, especially when working with numeric-like data such as months or other measurable entities. This decision seems to complicate certain use cases unnecessarily.

Imagine profil
Abandonează
Cel mai bun răspuns

Why not just define your field like this:

month = fields.Selection([
        (1, 'January'),
        (2, 'February'),
        (3, 'March'),
        (4, 'April'),
        (5, 'May'),
        (6, 'June'),
        (7, 'July'),
        (8, 'August'),
        (9, 'September'),
        (10, 'October'),
        (11, 'November'),
        (12, 'December')
    ], string='Month')

Imagine profil
Abandonează