Django 模型中的 ChoiceField [英] ChoiceField in Django model
问题描述
假设我的 Django 模型中有 ChoiceField
,其中包含多个选项.
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?
推荐答案
ChoiceFields 作为值存储在数据库中,因此以 文档:
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)
数据库将存储M"和F",所以如果有一天你决定像这样重命名它们*:
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'.
如果您想自己更改值(即M"和F"),那么您需要更新数据库,因此如果您想将M"更改为H",那么您需要使用 update
:
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')
除非你有充分的理由,否则我会避免这样做 - 因为你需要确保你对 GENDER_CHOICES
和你的 update
查询的更改是同时进行的.
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.
*是的,我知道这是一种愚蠢的翻译方式!
这篇关于Django 模型中的 ChoiceField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!