Specifying a mySQL ENUM in a Django model

前端 未结 9 1808
说谎
说谎 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:26

    http://www.b-list.org/weblog/2007/nov/02/handle-choices-right-way/

    class Entry(models.Model):
        LIVE_STATUS = 1
        DRAFT_STATUS = 2
        HIDDEN_STATUS = 3
        STATUS_CHOICES = (
            (LIVE_STATUS, 'Live'),
            (DRAFT_STATUS, 'Draft'),
            (HIDDEN_STATUS, 'Hidden'),
        )
        # ...some other fields here...
        status = models.IntegerField(choices=STATUS_CHOICES, default=LIVE_STATUS)
    
    live_entries = Entry.objects.filter(status=Entry.LIVE_STATUS)
    draft_entries = Entry.objects.filter(status=Entry.DRAFT_STATUS)
    
    if entry_object.status == Entry.LIVE_STATUS:
    

    This is another nice and easy way of implementing enums although it doesn't really save enums in the database.

    However it does allow you to reference the 'label' whenever querying or specifying defaults as opposed to the top-rated answer where you have to use the 'value' (which may be a number).

提交回复
热议问题