Django模型中的ChoiceField [英] ChoiceField in Django model
问题描述
如何实现?
class Foo(models.Model):
GENDER_CHOICES =(
('M','Male'),
('F','女'),
)
gender = models.CharField max_length = 1,choices = GENDER_CHOICES)
数据库将存储'M'和'F'如果你有一天决定重命名这些*:
class Foo(models.Model):
GENDER_CHOICES = (
('M','Homme'),
('F','Femme'),
)
gender = models.CharField(max_length = 1,choices = GENDER_CHOICES)
然后任何你使用扩展值'Male'或'Female'的任何地方现在都有'Homme'或'Femme'。
如果要更改值'M'和'F')本身,那么你需要更新数据库,所以如果你想将'M'改为'H',那么你可以使用 update
:
Foo.objects.filter(gender ='M')。update(gender ='H')
除非你有一个很好的理由,否则我会避免这样做 - 因为你需要确保你的更改为 GENDER_CHOICES
,您的更新
查询同时完成。
*是的,我知道这是一个愚蠢的翻译方式!
Suppose I have choicefield in my django model which consist of several choices. Now in future if I changed the existing choice (option) with some other name (choice), then whether the existing records in model with that choice(option) will also change? Or In admin page I need to set that new option manually?
How can I achieve this?
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!
这篇关于Django模型中的ChoiceField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!