Specifying a mySQL ENUM in a Django model

前端 未结 9 1809
说谎
说谎 2020-12-12 17:16

How do I go about specifying and using an ENUM in a Django model?

9条回答
  •  Happy的楠姐
    2020-12-12 17:34

    Django 3.0 has built-in support for Enums

    From the documentation:

    from django.utils.translation import gettext_lazy as _
    
    class Student(models.Model):
    
        class YearInSchool(models.TextChoices):
            FRESHMAN = 'FR', _('Freshman')
            SOPHOMORE = 'SO', _('Sophomore')
            JUNIOR = 'JR', _('Junior')
            SENIOR = 'SR', _('Senior')
            GRADUATE = 'GR', _('Graduate')
    
        year_in_school = models.CharField(
            max_length=2,
            choices=YearInSchool.choices,
            default=YearInSchool.FRESHMAN,
        )
    

    Now, be aware that it does not enforce the choices at a database level this is Python only construct. If you want to also enforce those value at the database you could combine that with database constraints:

    class Student(models.Model):
        ...
    
        class Meta:
            constraints = [
                CheckConstraint(
                    check=Q(year_in_school__in=YearInSchool.values),
                    name="valid_year_in_school")
            ]
    

提交回复
热议问题