How to set for m2m-field different querysets for each inline object?

158 views Asked by At

So I have a model that is shown in inline form. That model have ManyToManyField.

Imagine that there are several inline-objects that are already created.

The problem is how to show different querysets of available objects in my m2m-field based on original inline-object.

One more time:) I mean that in each inline-object must by m2m-field with different available variants. Variants will of course include all that is actually set for this inline-object + they must include only variants that are not present at the moment anywhere else.

Thanks.

1

There are 1 answers

0
Chris Pratt On

Question is very poorly written, so it's hard to be sure exactly what you're looking for, but my best guess is that you're want to limit the queryset for the ManyToManyField to items that are not assigned to anything else? If that's correct:

(You also didn't post an example model, so I'll make one up to illustrate)

class SomeModel(models.Model):
    my_m2m_field = models.ManyToManyField(OtherModel)

And, here's the code to limit the field based on that:

class SomeModelInlineAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyInlineAdminForm, self).__init__(*args, **kwargs)

        self.fields['my_m2m_field'].queryset = OtherModel.objects.filter(somemodel__isnull=True)

class SomeModelInlineAdmin(admin.TabularInline):
    model = SomeModel
    form = SomeModelInlineAdminForm