Home > Software engineering >  Use IntegerChoices in model Meta class
Use IntegerChoices in model Meta class

Time:10-29

I'm creating some constraints in my Meta class that reference an IntegerChoices enum. The issue I'm having is that I can't seem to figure out how to reference that IntegerChoices enum.

class MyModel(models.Model):
    States = models.IntegerChoices('States', 'PROGRESSING INSTALLED DELETED')

    state = models.PositiveSmallIntegerField(choices=States.choices, help_text='Defines the cluster\'s current state')

    class Meta:
        constraints = [
            models.CheckConstraint(check=models.Q(state__in=States), name='cluster_state_valid'),
        ]

self.States isn't working, no self object. MyModel.States isn't working either since MyModel isn't fully instantiated at this point.

Any advice/recommendation would be appreciated, thanks!

CodePudding user response:

I would advise that you define the enum outside the MyModel, such that it is interpreted first, so:

States = models.IntegerChoices('States', 'PROGRESSING INSTALLED DELETED')

class MyModel(models.Model):
    States = States
    state = models.PositiveSmallIntegerField(choices=States.choices, help_text='Defines the cluster\'s current state')

    class Meta:
        constraints = [
            models.CheckConstraint(check=models.Q(state__in=States.values), name='cluster_state_valid'),
        ]
  • Related