How to use enums as a choice field in django model

后端 未结 5 1721
情书的邮戳
情书的邮戳 2020-12-30 20:06

I have a model class of which I want two fields to be a choice fields, so to populate those choices I am using an enum as listed below

#models.py
class Trans         


        
5条回答
  •  失恋的感觉
    2020-12-30 20:21

    According to your reference from https://hackernoon.com/using-enum-as-model-field-choice-in-django-92d8b97aaa63. The choices should be list of tuple, while yours will return a tuple of tuple. More over i is different from i.name. Try:

    #enums.py
    class TransactionType(Enum):
    
        IN = "IN",
        OUT = "OUT"
    
        @classmethod
        def choices(cls):
            return [(i, i.value) for i in cls]
    

提交回复
热议问题