如何设置默认STATUSES
选项?
class Order(models.Model):
STATUSES = (
(u'E', u'Expected'),
(u'S', u'Sent'),
(u'F', u'Finished'),
)
status = models.CharField(max_length=2, null=True, choices=STATUSES)
答案 0 :(得分:43)
status = models.CharField(max_length=2, null=True, choices=STATUSES, default='E')
或者,如果STATUSES发生变化,则避免设置无效的默认值:
status = models.CharField(max_length=2, null=True, choices=STATUSES, default=STATUSES[0][0])
答案 1 :(得分:5)
这是一个古老的问题,只想添加现在可用的Djanto 3.x +语法:
class StatusChoice(models.TextChoices):
EXPECTED = u'E', 'Expected'
SENT = u'S', 'Sent'
FINISHED = u'F', 'Finished'
然后,您可以使用以下语法设置默认值:
status = models.CharField(
max_length=2,
null=True,
choices=StatusChoice.choices,
default=StatusChoice.EXPECTED
)