Python Django 模型多项选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27440861/
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-08-19 01:48:57  来源:igfitidea点击:

Django Model MultipleChoice

pythondjangodjango-models

提问by AlvaroAV

I know there isn't MultipleChoiceFieldfor a Model, you can only use it on Forms.

我知道没有MultipleChoiceField一个模式,你只能用它的形式。

Today I face an issue when analyzing a new project related with Multiple Choices.

今天,我在分析与多项选择相关的新项目时遇到了一个问题。

I would like to have a field like a CharFieldwith choiceswith the option of multiple choice.

我想要一个CharField带有choices多项选择选项的字段。

I solved this issue other times by creating a CharFieldand managed the multiple choices in the form with a forms.MultipleChoiceFieldand store the choices separated by commas.

我在其他时候通过创建 a 解决了这个问题,CharField并用 a管理表单中的多个选项,forms.MultipleChoiceField并存储用逗号分隔的选项。

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 NOTto edit the Django admin formneitheruse forms. I need a Model Field with multiple choices option

在这个项目中,由于配置,我不能这样做,因为我上面提到的,我需要做的是在型号,我宁愿来编辑Django管理形式既不使用形式。我需要一个带有多项选择选项的模型字段

  • Have someone solved anything like this via Models ?
  • 有人通过 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 simplechoices, 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 choicesnot only 1 choice.

但具有保存多项选择的能力,而不仅仅是一项选择。

采纳答案by spookylukey

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-multiselectfield这样的解决方案

回答by Matias Herranz

From the two, https://pypi.python.org/pypi/django-select-multiple-field/looks more well rounded and complete. It even has a nice set of unittests.

从两者来看,https://pypi.python.org/pypi/django-select-multiple-field/看起来更加全面和完整。它甚至有一套很好的单元测试。

The problem I found is that it throws a Django 1.10 deprecation warning in the class that implements the model field.

我发现的问题是它在实现模型字段的类中引发了 Django 1.10 弃用警告。

I fixed this and sent a PR. The latest code, until they merge my PR (if they ever decide to hehe) is in my fork of the repo, here: https://github.com/matiasherranz/django-select-multiple-field

我解决了这个问题并发送了 PR。最新的代码,直到他们合并我的 PR(如果他们决定嘿嘿)在我的 repo 分支中,在这里:https: //github.com/matiasherranz/django-select-multiple-field

Cheers!

干杯!

M.-

M.-

回答by lechup

In case You are using Postgres consider using ArrayField.

如果您使用 Postgres,请考虑使用ArrayField

from django.db import models
from django.contrib.postgres.fields import ArrayField

class WhateverModel(models.Model):
    WHATEVER_CHOICE = u'1'
    SAMPLE_CHOICES = (
        (WHATEVER_CHOICE, u'one'),
    )
    choices = ArrayField(
        models.CharField(choices=SAMPLE_CHOICES, max_length=2, blank=True, default=WHATEVER_CHOICE),
    )

回答by Risadinha

If you want the widget to look like a text input and still be able to allow selecting several options from suggestions, you might be looking for Select2. There is also django-select2that integrates it with Django Forms and Admin.

如果您希望小部件看起来像文本输入,并且仍然能够允许从建议中选择多个选项,您可能正在寻找Select2。还有django-select2将它与 Django Forms 和 Admin 集成。

回答by younesfmgtc

The easiest way I found (just I use eval() to convert string gotten from input to tuple to read again for form instance or other place)

我找到的最简单的方法(只是我使用 eval() 将从输入获得的字符串转换为元组以再次读取表单实例或其他地方)

This trick works very well

这个技巧效果很好

#model.py
class ClassName(models.Model):
    field_name = models.CharField(max_length=100)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.field_name:
            self.field_name= eval(self.field_name)



#form.py
CHOICES = [('pi', 'PI'), ('ci', 'CI')]

class ClassNameForm(forms.ModelForm):
    field_name = forms.MultipleChoiceField(choices=CHOICES)

    class Meta:
        model = ClassName
        fields = ['field_name',]

#view.py
def viewfunction(request, pk):
    ins = ClassName.objects.get(pk=pk)

    form = ClassNameForm(instance=ins)
    if request.method == 'POST':
        form = form (request.POST, instance=ins)
        if form.is_valid():
            form.save()
            ...