1

I have a Django admin class which declares an inlines iterable. Something like:

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    ...
    ...
    inlines = [CategoryModifiersInline,]
    ...
    ...

Then I have an Inline admin class like this:

class CategoryModifiersInline(admin.TabularInline):

    model = Category.modifiers.through
    fk_name = 'category'
    extra = 1 


    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        qs = Product.objects.filter(is_modifier=True).filter(active=True)
        kwargs['queryset'] = qs
        return super(CategoryModifiersInline, self).formfield_for_foreignkey(db_field, request, **kwargs)

Where I filter the queryset for the foreign key based on some business requirement.

This inline is only showed to the user in the change view, that means, when an object of the class Category is created and the user wants to add modifiers to it, never in the add view.

What I want to do, is filtering the foreign key by one of the attributes of the Category model, I mean, I want to access the parent object from the formfield_for_foreignkey method.

Does anyone know a way to achieve that?

1 Answers1

2

Well I found a similar question here in StackOverflow, and used the method described there to solve it.

It uses the parent_model attribute from inlines, and the resolve method from django.core.urlresolvers to get the instance based in the url.

Here's the code:

    def get_object(self, request):
        resolved = resolve(request.path_info)
        if resolved.args:
             return self.parent_model.objects.get(pk=resolved.args[0])
        return None

Then I would call the get_object method inside of my formfield_from_foreignkey method to get the instance of the object I want to use as a filter.

Hope it helps!

Community
  • 1
  • 1