python 除了 ManyToMany 之外,是否有允许多种选择的 Django ModelField?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2267332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:13:07  来源:igfitidea点击:

Is there a Django ModelField that allows for multiple choices, aside from ManyToMany?

pythondjangoforms

提问by int3

I'd like the user to be able to make multiple selections via the admin interface, and store the result as a list of comma-separated values. A select-multiple or a list of checkboxes would be great. However, I don't need the items in this list of values to refer to any models in particular... I just want a text list of items, plain and simple, hence I don't think the ManyToManyField is the one I'm looking for. What's the quickest way to do this in Django?

我希望用户能够通过管理界面进行多项选择,并将结果存储为逗号分隔值列表。选择多个或复选框列表会很棒。但是,我不需要这个值列表中的项目来特别引用任何模型......我只想要一个文本项目列表,简单明了,因此我不认为 ManyToManyField 是我的我在找。在 Django 中执行此操作的最快方法是什么?

采纳答案by Alexander Torstling

There is a django snippet which does just this: multiple choice model field. It says:

有一个 django 片段可以做到这一点:多项选择模型字段。它说:

Usually you want to store multiple choices as a manytomany link to another table. Sometimes however it is useful to store them in the model itself. This field implements a model field and an accompanying formfield to store multiple choices as a comma-separated list of values, using the normal CHOICES attribute.

通常,您希望将多个选项存储为指向另一个表的多条链接。然而,有时将它们存储在模型本身中很有用。该字段实现了一个模型字段和一个伴随的表单字段,以使用普通的 CHOICES 属性将多个选择存储为逗号分隔的值列表。

回答by Mick T

Django-multiselectfield does what you require:

Django-multiselectfield 做你需要的:

https://github.com/goinnn/django-multiselectfield

https://github.com/goinnn/django-multiselectfield

It's inspired by the snippet that Alexander mentioned.

它的灵感来自亚历山大提到的片段。

回答by jkatzer

This django snippet accomplishes the same with a much smaller footprint.

这个 django 片段以更小的占用空间完成了同样的任务。

http://djangosnippets.org/snippets/23/

http://djangosnippets.org/snippets/23/

make sure to update those imports since they are pre version 1.0

确保更新这些导入,因为它们是 1.0 版之前的