ChoiceField in Django model

前端 未结 1 537
名媛妹妹
名媛妹妹 2020-12-04 14:09

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 o

1条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 14:43

    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!

    0 讨论(0)
提交回复
热议问题