Search code examples
pythondjangodjango-modelsdjango-model-field

Django model choice Text to Integer


I'm trying to create a django model using Text as a value for the IntegerField

class User(models.Model):

    class UserRole(models.IntegerChoices):
        FULLACCESS = 0, _('full_access_user')
        READONLY = 1, _('read_only_user')
        WRITEONLY = 2, _('write_only_user')

    role = models.IntegerField(choices=UserRole.choices)

When I try to create the user like User.objects.create(role="full_access_user") it does not map the string value to integer. Tried to define models.IntegerChoices as models.TextChoices and map those to integer but django forbids such action. What could be done to create the object like it's shown in the example ?


Solution

  • If you just need a sane way of accessing these values, the standard way of doing this is by defining constants in your class:

    class User(models.Model):
        ROLE_FULL_ACCESS = 0
        ROLE_READ_ONLY = 1
        ROLE_WRITE_ONLY = 2
        ROLE_CHOICES = [
            (ROLE_FULL_ACCESS, 'Full Access'),
            (ROLE_READ_ONLY, 'Read Only'),
            (ROLE_WRITE_ONLY, 'Write Only'),
        ]
    
        role = models.IntegerField(choices=ROLE_CHOICES)
    

    Usage:

    User.objects.create(role=User.ROLE_FULL_ACCESS)
    

    You could refactor this further but unless you'll actually reuse the resulting code somewhere else, it's usually unnecessary as the above would be able to cover ~99% of what you need to do.