Django ModelMultipleChoiceField问题无法保存数据到数据库中。

huangapple go评论60阅读模式
英文:

Django ModelMultipleChoiceField problem to save data in DB

问题

You should use a models.ManyToManyField field in models.py to make it work again. Here's the updated code:

models.py

from django.db import models

class Record(models.Model):
    testrever = models.ManyToManyField('YourModelNameHere')

Replace 'YourModelNameHere' with the actual name of the model you want to use for the testrever field. This will allow you to establish a many-to-many relationship with another model, which should work for your scenario.

英文:

I used to have a Multi select box in my form filled with a JSON list

forms.py

FRUIT_CHOICES= [
    ('Oranges', 'Oranges'),
    ('Cantaloupes', 'Cantaloupes'),
    ('Mangoes', 'Mangoes'),
    ('Honeydews', 'Honeydews')
    ]

class AddRecordForm(forms.ModelForm):
    testrever = forms.MultipleChoiceField(choices=FRUIT_CHOICES)

And so I used a JSON field in my models.py like this

models.py

class Record(models.Model):
    testrever = models.JSONField(max_length=500)

It worked like a charm and I was able to save the selection and load it back when the form was recalled.

But now in forms.py I need to modify the forms.MultipleChoiceField to forms.ModelMultipleChoiceField which is populated by a queryset like this

class AddRecordForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        self.storage_pk = kwargs.pop('pk')
        super(AddRecordForm, self).__init__(*args, **kwargs)
        self.fields['testrever'].queryset = BDC.objects.filter(ref=self.storage_pk).values_list('model', flat=True) 


    testrever = forms.ModelMultipleChoiceField(widget=forms.widgets.SelectMultiple, queryset=None)

class Meta:
    model = Record
    exclude = ("user",)
    fields = ['id','first_name','last_name','email', 'phone' ,'address', 'city' ,'state' ,'zipcode' ,'regarde' ,'testrever']

So now my models.JSONField in models.py is no longer working since I'm not rendering a JSON list format anymore.

What kind of field should I use in models.py to make it work again?

答案1

得分: 1

如果您选择另一个模型的零个、一个或多个项目,则使用ManyToManyField&nbsp;<sup>[Django-doc]</sup>

<pre><code>class Fruit(models.Model):
name = models.CharField(max_length=128, unique=True)

def __str__(self):
    return name

class Record(models.Model):
testrever = models.<b>ManyToManyField(</b>Fruit, blank=True<b>)</b></code></pre>

这也使用ModelMultipleChoice字段作为默认表单字段。因此,您只需插入不同的小部件:

<pre><code>class RecordForm(forms.ModelForm):
class Meta:
model = Record
fields = 'all'
widgets = {'testrever': <b>forms.SelectMultiple</b>}</code></pre>

虽然大多数数据库现在提供JSON字段,这对于非结构化数据很有用,但对于结构化数据来说,使用JSONField不是一个好主意,因为它违反了第一范式&nbsp;<sup>[维基]</sup>

英文:

If you pick zero, one or multiple items of another model, you use a ManyToManyField&nbsp;<sup>[Djangp-doc]</sup>:

<pre><code>class Fruit(models.Model):
name = models.CharField(max_length=128, unique=True)

def __str__(self):
    return name

class Record(models.Model):
testrever = models.<b>ManyToManyField(</b>Fruit, blank=True<b>)</b></code></pre>

This also uses a ModelMultipleChoice field as default form field. So you only have to plug in a different widget:

<pre><code>class RecordForm(forms.ModelForm):
class Meta:
model = Record
fields = 'all'
widgets = {'testrever': <b>forms.SelectMultiple</b>}</code></pre>

while most databases offer a JSON field nowadays, which is useful for unstructered data, for structured data, using a JSONField is not a good idea as it violates first normal form&nbsp;<sup>[wiki]</sup>.

huangapple
  • 本文由 发表于 2023年5月18日 03:09:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76275470.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定