Specifying a mySQL ENUM in a Django model

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

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

相关标签:
9条回答
  • 2020-12-12 17:38

    From the Django documentation:

    MAYBECHOICE = (
        ('y', 'Yes'),
        ('n', 'No'),
        ('u', 'Unknown'),
    )
    

    And you define a charfield in your model :

    married = models.CharField(max_length=1, choices=MAYBECHOICE)
    

    You can do the same with integer fields if you don't like to have letters in your db.

    In that case, rewrite your choices:

    MAYBECHOICE = (
        (0, 'Yes'),
        (1, 'No'),
        (2, 'Unknown'),
    )
    
    0 讨论(0)
  • 2020-12-12 17:40

    A the top of your models.py file, add this line after you do your imports:

        enum = lambda *l: [(s,_(s)) for s in l]
    
    0 讨论(0)
  • 2020-12-12 17:42

    There're currently two github projects based on adding these, though I've not looked into exactly how they're implemented:

    1. Django-EnumField:
      Provides an enumeration Django model field (using IntegerField) with reusable enums and transition validation.
    2. Django-EnumFields:
      This package lets you use real Python (PEP435-style) enums with Django.

    I don't think either use DB enum types, but they are in the works for first one.

    0 讨论(0)
提交回复
热议问题