belisasun
belisasun

Reputation: 565

Django choices. How to set default option?

How to set default STATUSES option ?

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)

Upvotes: 48

Views: 37666

Answers (2)

Mehdi Zare
Mehdi Zare

Reputation: 1381

It's an old question, just wanted to add the now availabel Djanto 3.x+ syntax:

class StatusChoice(models.TextChoices):
    EXPECTED = u'E', 'Expected'
    SENT = u'S', 'Sent'
    FINISHED = u'F', 'Finished'

Then, you can use this syntax to set the default:

status = models.CharField(
    max_length=2,
    null=True,
    choices=StatusChoice.choices,
    default=StatusChoice.EXPECTED
)

Upvotes: 17

rockingskier
rockingskier

Reputation: 9346

status = models.CharField(max_length=2, null=True, choices=STATUSES, default='E')

or to avoid setting an invalid default if STATUSES changes:

status = models.CharField(max_length=2, null=True, choices=STATUSES, default=STATUSES[0][0])

Upvotes: 78

Related Questions