在模型 Meta class 中使用 IntegerChoices

Use IntegerChoices in model Meta class

我正在我的 Meta class 中创建一些引用 IntegerChoices 枚举的约束。我遇到的问题是我似乎无法弄清楚 如何 来引用 IntegerChoices 枚举。

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 不工作,没有 self 对象。 MyModel.States 也不起作用,因为此时 MyModel 尚未完全实例化。

任何 advice/recommendation 将不胜感激,谢谢!

我建议您在 MyModel 之外定义枚举,以便首先对其进行解释,因此:

<strong>States</strong> = models.IntegerChoices('States', 'PROGRESSING INSTALLED DELETED')

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

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