Django 模型多项选择 [英] Django Model MultipleChoice
问题描述
我知道模型没有MultipleChoiceField
,您只能在表单上使用它.
今天,我在分析与多项选择相关的新项目时遇到一个问题.
我想要一个像 CharField
这样的字段,带有 choices
和多选选项.
我其他时候通过创建一个 CharField
解决了这个问题,并使用 forms.MultipleChoiceField
管理表单中的多项选择,并存储以逗号分隔的选择.>
在这个项目中,由于配置,我不能像上面提到的那样做,我需要在模型中做,我更喜欢NOT编辑Django管理表单 都不使用表格.我需要一个带有多项选择选项的模型字段
- 有人通过模型解决过类似的问题吗?
也许覆盖某些模型功能或使用自定义小部件...我不知道,我有点迷失在这里.
编辑
我知道简单的选择,我想要类似的东西:
class MODEL(models.Model):我的选择 = (('a', 'Hola'),('b', '你好'),('c', '卓悦'),('d', 'Boas'),)......my_field = models.CharField(max_length=1,选择=MY_CHOICES)...
但具有保存多项选择而不仅仅是一项选择的能力.
您需要考虑如何在数据库级别存储数据.这将决定您的解决方案.
据推测,您希望表中的单个列存储多个值.这也将迫使您考虑如何序列化 - 例如,如果您需要存储可能包含逗号的字符串,则不能简单地使用逗号分隔.
但是,您可能最好使用像 django-multiselectfield
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.
I would like to have a field like a CharField
with choices
with the option of multiple choice.
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.
Edit
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)
...
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 you will serialize - for example, you can't simply do comma separated if you need to store strings that might contain commas.
However, you are probably best off using a solution like django-multiselectfield
这篇关于Django 模型多项选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!