Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use IntegerChoices in model Meta class

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!

like image 409
Will Gordon Avatar asked Jul 19 '26 22:07

Will Gordon


1 Answers

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'),
        ]
like image 71
Willem Van Onsem Avatar answered Jul 22 '26 14:07

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!