I had a similar problem as this question on StackOverflow where I was getting a NameError that the ModelName wasn’t defined when I tried to migrate the changes after adding a TextChoices class and CheckConstraint within Meta trying to reference the choices (like ModelName.TextChoiceClassName.CHOICE_A).
Just wanting to double-check: is the below (found in the StackOverflow response) normally how this problem is handled? So you move the TextChoices class outside of the model it’s being used in and then add an OrderStatusChoices = OrderStatusChoices so that you can still reference Order.OrderStatusChoices.CANCELLED elsewhere?
class OrderStatusChoices(models.TextChoices):
...
class Order(models.Model):
OrderStatusChoices = OrderStatusChoices
...
class Meta:
constraints = [
models.CheckConstraint(
name='%(app_label)s_%(class)s_status_valid',
check=models.Q(status__in=OrderStatusChoices.values)
)
]