Login

Limit queryset to objects related to parent in ManyToMany fields within admin inlines

Author:
DrMeers
Posted:
May 27, 2010
Language:
Python
Version:
1.2
Tags:
limit_choices_to ManyToMany ManyToManyField admin inline formfield_for_manytomany
Score:
4 (after 4 ratings)

formfield_for_manytomany allows you to limit the choices/queryset for a ManyToManyField, but without direct access to the parent object. This snippet stores a reference to the parent object in get_formset and allows limiting of ManyToManyFields to objects related to the same parent object. See ExampleInline for example usage.

If for some reason you have a ManyToManyField in a TabularInline, just change the template in the subclass.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from django.contrib import admin

class InlineWithLimitedManyToManyFields(admin.StackedInline):
    limited_manytomany_fields = {}
    
    def get_formset(self, request, obj=None, **kwargs):
        # Hack! Hook parent obj just in time to use in formfield_for_manytomany
        self.parent_obj = obj
        return super(InlineWithLimitedManyToManyFields, self).get_formset(
            request, obj, **kwargs)
    
    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name in self.limited_manytomany_fields.keys() and \
               hasattr(self,'parent_obj'):
            kwargs['queryset'] = db_field.rel.to.objects.filter(**{
                self.limited_manytomany_fields[db_field.name]: self.parent_obj
                })
        return super(
            InlineWithLimitedManyToManyFields, self).formfield_for_manytomany(
            db_field, request, **kwargs)


class ExampleInline(InlineWithLimitedManyToManyFields):
    model = ExampleModel
    limited_manytomany_fields = {
        'first_many_to_many_field_name':
            'field_name_for_foreignkey_in_related_model_to_parent',
        'second_many_to_many_field_name':
            'field_name_for_foreignkey_in_related_model_to_parent',
        }    

More like this

  1. ManyToManyField no syncdb by powerfox 6 years, 6 months ago
  2. ManyToManyField that can be set even if it relies on a intermediary model. by quiesagua 3 years, 1 month ago
  3. Find deletable objects by writefaruq 4 years, 1 month ago
  4. Admin action for a "CSV Export" with ManyToManyField by CarlosRodriguez 1 year, 1 month ago
  5. RelatedNullFilterSpec: django-admin custom filter all/null/not null/choices by Codeko 4 years, 9 months ago

Comments

mhulse (on May 24, 2011):

Could someone provide an example of what the model should look like? I don't really understand what "field_name_for_foreignkey_in_related_model_to_parent" means; do I have to put a FK in the "inline" model???

Thanks! M

#

normic (on June 17, 2015):

@mhulse: field_name_for_foreignkey_in_related_model_to_parent means you should name the field which should be used for filtering the many to many, usually the ForeignKey field which connects your M2M with the "Parent".

Note for everyone: This still works with Django 1.8

#

Please login first before commenting.