For Django3.0+, use models.TextChoices
(see docs-v3.0 for enumeration types)
from django.db import models
class MyModel(models.Model):
class Month(models.TextChoices):
JAN = '1', "JANUARY"
FEB = '2', "FEBRUARY"
MAR = '3', "MAR"
# (...)
month = models.CharField(
max_length=2,
choices=Month.choices,
default=Month.JAN
)
Usage::
>>> obj = MyModel.objects.create(month='1')
>>> assert obj.month == obj.Month.JAN
>>> assert MyModel.Month(obj.month).label == 'JANUARY'
>>> assert MyModel.objects.filter(month=MyModel.Month.JAN).count() >= 1
>>> assert MyModel.Month(obj.month).name == 'JAN'
>>> obj2 = MyModel(month=MyModel.Month.FEB)
>>> assert obj2.get_month_display() == obj2.Month(obj2.month).label
Personally, I would rather use models.IntegerChoices
class MyModel(models.Model):
class Month(models.IntegerChoices):
JAN = 1, "JANUARY"
FEB = 2, "FEBRUARY"
MAR = 3, "MAR"
# (...)
month = models.PositiveSmallIntegerField(
choices=Month.choices,
default=Month.JAN
)
Example::
class PaidBy(models.IntegerChoices):
wx = 0, '微信'
ali = 1, '支付宝'
other = 2, '其他'
class Record(models.Model):
pay_by = models.PositiveSmallIntegerField('支付方式', choices=PaidBy.choices, default=PaidBy.wx)