Opened 5 years ago

Closed 5 years ago

#30233 closed New feature (wontfix)

add get_queryset_with_parent_obj to InlineModelAdmin to support access parent_model's instance

Reported by: banxi Owned by: nobody
Component: contrib.admin Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

When subclass admin.InlineModelAdmin.
I want to limit the queryset related to the parent_models's instance.

In my usecase, there's a Org Tree Model. and We can set managers for Org. So I used the following ManyToManyField inline:

class OrgManagerRelationInline(admin.TabularInline):
    model = OrgManagerRelation
    extra = 1

    def get_queryset(self, request):
        qs = super(OrgManagerRelationInline, self).get_queryset(request)
        return qs

But I want to limit to the manager candicates only belong to higher org levels.
So I need to access the parent_model's instance. and there's also a SO question
https://stackoverflow.com/questions/32150088/django-access-the-parent-instance-from-the-inline-model-admin
But I dont'k want to use to unrobust hacking method.

So think we should provide a get_queryset_with_parent_obj or something like this.

    def get_queryset(self, request):
        queryset = super().get_queryset(request)
        if not self.has_view_or_change_permission(request):
            queryset = queryset.none()
        return queryset

    def get_queryset_with_parent_obj(self,request,parent_obj):
        return self.get_queryset(request)

and the calling code in _create_formsets can be changed to :

            formset_params = {
                'instance': obj,
                'prefix': prefix,
                'queryset': inline.get_queryset_with_parent_obj(request,parent_obj=obj),
            }

Change History (1)

comment:1 by Carlton Gibson, 5 years ago

Resolution: wontfix
Status: newclosed

You can already solve this using `ModelAdmin.get_inline_instances()`. This is passed the parent object, which you could set as an attribute on the inline, to be used later in get_queryset().

Note: See TracTickets for help on using tickets.
Back to Top