Django模型中的ChoiceField [英] ChoiceField in Django model

查看:102
本文介绍了Django模型中的ChoiceField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的django模型中有choicefield,它包含几个选择。现在在将来如果我改变现有的选择(选项)与一些其他名称(选择),那么模型中现有的记录与选择(选项)是否也会改变?或者在管理页面中,需要手动设置新选项?



如何实现?

ChoiceFields作为值存储在数据库中,所以以文档

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆