[Fixed]-Django limit_choices_to on ManyToMany related with Inline

1👍

I don’t know why limit_choices_to doesn’t work for the inline field, I am having the same problem. While this should not be necessary, you can limit the queryset of a field in an inline using this answer: https://stackoverflow.com/a/4236159/1302095

This is an old answer to an old question, so I’m not sure if there are better ways in newer versions of django. I am using 1.8.3 and it works, which is what matters to me!

Code pasted here for reference:

class RoomInline(admin.TabularInline):
    model = Room

    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
        field = super(RoomInline, self).formfield_for_foreignkey(db_field, request, **kwargs)

        if db_field.name == 'inside_room':
            if request._obj_ is not None:
                field.queryset = field.queryset.filter(building__exact = request._obj_)  
            else:
                field.queryset = field.queryset.none()

        return field

class BuildingAdmin(admin.ModelAdmin):
    inlines = (RoomInline,)

    def get_form(self, request, obj=None, **kwargs):
        # just save obj reference for future processing in Inline
        request._obj_ = obj
        return super(BuildingAdmin, self).get_form(request, obj, **kwargs)

Leave a comment