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 ManyToManyField
s 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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
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
#
@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
#
That's work fine for me. But I made some modifications:
Code:
Sample:
#
Oups: Corrected sample:
#
Please login first before commenting.