[Answer]-Django models many-to-many relations issue

1👍

First option is to override save method in Model_1 and on every save operation update inspectors in specially created model Model1inspectors. This way `Model_2′ will look just like yours from question.

But i think it’s better to customize queryset for that ManyToManyField in your form like this:

class Model_2Form(forms.ModelForm):
    class Meta:
        model = Model_2

    def __init__(self, *args, **kwargs):
        super(Model_2Form, self).__init__(*args, **kwargs)
        self.fields['model_1_inspectors'].queryset = InspectorData.objects.filter(
            pk__in=Model_1.objects.values('inspectors').distinct())
👤ndpu

0👍

import the model required as

from myapp_folder.models import Inspector
class Model_2(models.Model):
    model_1_inspectors = ManyToManyField(Inspector)

This will work

Leave a comment