41

如何设置默认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)
4

2 回答 2

70
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])
于 2012-10-04T10:55:53.303 回答
11

这是一个老问题,只是想添加现在可用的 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
)
于 2020-03-29T17:22:46.540 回答