[Django]-Django enum attribute equality

4👍

The reason that this happens is because the choices call str on the value that is given, and this thus means it will store "AwesomeNess.slight" as a string (if that is set as default).

Since , you can work with a TextChoices class [Django-doc] which is quite the same as using an Enum. You thus can define a TextChoices model with:

class Choice(models.Model):

    class AwesomNess(models.TextChoices):
        SLIGHT = 'SLIGHT', 'slight'
        VERY = 'VERY', 'very'

    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    awesomeness = models.CharField(
        max_length=255,
        choices=AwesomeNess.choices,
        default=AwesomeNess.SLIGHT
    )

for older versions, you need to specify that you work with the value of the AwesomeNess:

class AwesomeNess(Enum):
    slight = 'SLIGHT'
    very = 'VERY'

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    awesomeness = models.CharField(
        max_length=255,
        choices=[(tag.value, tag.name) for tag in AwesomeNess],
        default=AwesomeNess.slight.value
    )

Leave a comment