在这个项目中,由于配置,我不能像上面提到的那样做,我需要在模型中做,我更喜欢NOT编辑Django管理表单 都不使用表格.我需要一个带有多项选择选项的模型字段有人通过模型解决过类似的问题吗?也许覆盖某些模型功能或使用自定义小部件...我不知道,我有点迷失在这里.编辑我知道简单的选择,我想要类似的东西:class MODEL(models.Model):我的选择 = (('a', 'Hola'),('b', '你好'),('c', '卓悦'),('d', 'Boas'),)......my_field = models.CharField(max_length=1,选择=MY_CHOICES)...但具有保存多项选择而不仅仅是一项选择的能力. 解决方案 您需要考虑如何在数据库级别存储数据.这将决定您的解决方案.据推测,您希望表中的单个列存储多个值.这也将迫使您考虑如何序列化 - 例如,如果您需要存储可能包含逗号的字符串,则不能简单地使用逗号分隔.但是,您可能最好使用像 django-multiselectfieldI 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 optionHave 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.EditI'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 模型多项选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-30 07:34