[Answered ]-Django ModelMultipleChoiceField problem to save data in DB

1๐Ÿ‘

โœ…

If you pick zero, one or multiple items of another model, you use a ManyToManyFieldย [Djangp-doc]:

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

    def __str__(self):
        return name


class Record(models.Model):
    testrever = models.ManyToManyField(Fruit, blank=True)

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

class RecordForm(forms.ModelForm):
    class Meta:
        model = Record
        fields = '__all__'
        widgets = {'testrever': forms.SelectMultiple}

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ย [wiki].

Leave a comment