Use IntegerChoices in model Meta class

Issue

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!

Solution

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'),
        ]

Answered By – Willem Van Onsem

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published