ChoiceField in Django model ChoiceField in Django model django django

ChoiceField in Django model


ChoiceFields are stored in the database as the values, so to take an example from the documentation:

class Foo(models.Model):    GENDER_CHOICES = (        ('M', 'Male'),        ('F', 'Female'),    )    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)

The database will store 'M' and 'F', so if you one day decide to rename those like this*:

class Foo(models.Model):    GENDER_CHOICES = (        ('M', 'Homme'),        ('F', 'Femme'),    )    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)

Then anywhere you use the expanded values 'Male' or 'Female' will now have 'Homme' or 'Femme'.

If you want to change the values (i.e. 'M' and 'F') themselves, then you'll want to update the database, so if you wanted to change 'M' to 'H', then you'd use update:

Foo.objects.filter(gender = 'M').update(gender = 'H')

Unless you've got a good reason to, I'd avoid doing this - since you'll need to make sure your change to GENDER_CHOICES and your update query are done simultaneously.

*And yes, this I know this is a stupid way to do translation!