How to use enums as a choice field in django model

后端 未结 5 1697
情书的邮戳
情书的邮戳 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:41

    Problem in your code is that INITIATED = "INITIATED", a comma after INITIATED option and other options. when we add comma after any string it will become a tuple. See an example below

    s = 'my str'
    print(type(s))
    # output: str
    
    s = 'my str',
    print(type(s))
    # output: tuple
    

    models.py

    class Transaction(models.Model):
        trasaction_status = models.CharField(max_length=255, choices=TransactionStatus.choices())
        transaction_type = models.CharField(max_length=255, choices=TransactionType.choices())
    

    enums.py

    class TransactionType(Enum):
    
        IN = "IN"
        OUT = "OUT"
    
        @classmethod
        def choices(cls):
            print(tuple((i.name, i.value) for i in cls))
            return tuple((i.name, i.value) for i in cls)
    
    class TransactionStatus(Enum):
    
        INITIATED = "INITIATED"
        PENDING = "PENDING"
        COMPLETED = "COMPLETED"
        FAILED = "FAILED"
        ERROR = "ERROR"
    
        @classmethod
        def choices(cls):
            print(tuple((i.name, i.value) for i in cls))
            return tuple((i.name, i.value) for i in cls)
    

提交回复
热议问题