52

Suppose I have ChoiceField in my Django model which consist of several choices.

Now, in the future if I changed the existing choice (option) with some other name (choice), will the existing records in the model with that choice (option) also change? Do I need to set that new option manually in the admin page?

daaawx
  • 3,273
  • 2
  • 17
  • 16
Asif
  • 619
  • 1
  • 8
  • 9

1 Answers1

150

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!

Dominic Rodger
  • 97,747
  • 36
  • 197
  • 212