Django Model MultipleChoice [英] Django Model MultipleChoice
问题描述
我知道模型不存在 MultipleChoiceField
,您只能在表单上使用。
I know there isn't MultipleChoiceField
for a Model, you can only use it on Forms.
今天,在分析与多个选择相关的新项目时,我遇到了一个问题。
Today I face an issue when analyzing a new project related with Multiple Choices.
我想要有一个类似 CharField
与选择
可以选择多项选择。
I would like to have a field like a CharField
with choices
with the option of multiple choice.
我曾经通过创建一个 CharField
来解决这个问题,并以 forms.MultipleChoiceField
并存储由逗号分隔的选项。
I solved this issue other times by creating a CharField
and managed the multiple choices in the form with a forms.MultipleChoiceField
and store the choices separated by commas.
在这个项目中,由于配置,我不能这样做我上面提到,我需要在模型中做,而且我更喜欢不来编辑使用表单 。 我需要一个具有多个选项的模型字段
In this project, due to configuration, I cannot do it as I mention above, I need to do it in the Models, and I prefer NOT to edit the Django admin form neither use forms. I need a Model Field with multiple choices option
- 有人通过模型解决了这样的问题吗? >
- Have someone solved anything like this via Models ?
也许覆盖一些模型功能或使用自定义窗口小部件...我不知道,我有点迷失在这里。
Maybe overriding some of the models function or using a custom widget... I don't know, I'm kinda lost here.
简单的选择,我想有一些类似的东西:
I'm aware off simple choices, I would like to have something like:
class MODEL(models.Model):
MY_CHOICES = (
('a', 'Hola'),
('b', 'Hello'),
('c', 'Bonjour'),
('d', 'Boas'),
)
...
...
my_field = models.CharField(max_length=1, choices=MY_CHOICES)
...
,但具有保存多个选项的功能不仅1选择。
but with the capability of saving multiple choices not only 1 choice.
推荐答案
您需要考虑如何在数据库级存储数据。这将决定您的解决方案。
You need to think about how you are going to store the data at a database level. This will dictate your solution.
大概您希望在表中存储多个值的单个列。这也将迫使您考虑如何序列化 - 例如,如果需要存储可能包含逗号的字符串,则不能简单地使用逗号分隔。
Presumably, you want a single column in a table that is storing multiple values. This will also force you to think about how to will serialize - for example, you can't simply do comma separated if you need to store strings that might contain commas.
但是,您最好使用以下解决方案之一:
However, you are best using a solution like one of the following:
https://pypi.python.org/pypi/django -select-multiple-field /
这篇关于Django Model MultipleChoice的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!