13

I'm having some trouble overriding the queryset for my inline admin.

Here's a bog-standard parent admin and inline admin:

class MyInlineAdmin(admin.TabularInline):
    model = MyInlineModel
    def queryset(self, request):
        qs = super(MyInlineAdmin, self).queryset(request)
        return qs

class ParentAdmin(admin.ModelAdmin):
    inlines = [MyInlineAdmin]
admin.site.register(ParentAdminModel, ParentAdmin)

Now I can do qs.filter(user=request.user) or qs.filter(date__gte=datetime.today()) no problem.

But what I need is either the MyInlineModel instance or the ParentAdminModel instance (not the model!), as I need to filter my queryset based on that.

Is it possible to get something like self.instance or obj (like in get_readonly_fields() or get_formset()) inside the queryset() method?

Hope this makes sense. Any help is much appreciated.

Nunser
  • 4,512
  • 8
  • 25
  • 37
  • http://stackoverflow.com/questions/14950193/how-to-get-the-current-model-instance-from-inlineadmin-in-django might be helpful – Christian Schmizz Sep 02 '13 at 15:17
  • Note that in Django 1.6 the queryset method was renamed to get_queryset. https://docs.djangoproject.com/en/dev/releases/1.6/#get-query-set-and-similar-methods-renamed-to-get-queryset – jenniwren Aug 21 '15 at 19:56

1 Answers1

8
class MyInlineAdmin(admin.TabularInline):
    model = MyInlineModel
    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
        """enable ordering drop-down alphabetically"""
        if db_field.name == 'car':
            kwargs['queryset'] = Car.objects.order_by("name") 
        return super(MyInlineAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

class ParentAdmin(admin.ModelAdmin):
    inlines = [MyInlineAdmin]

admin.site.register(ParentAdminModel, ParentAdmin)

Im assuming your models look something like:

class MyInlineModel(models.Model):
    car=models.Foreignkey(Car)
    #blah

for more on this; read the django Docs on formfield_for_foreignkey--> https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey

Williams
  • 4,044
  • 1
  • 37
  • 53
Komu
  • 14,174
  • 2
  • 28
  • 22
  • 1
    This doesn't work at all. The `formfield_for_foreignkey` is for dropdown and similar widgets. See [this solution](http://stackoverflow.com/questions/6703652/limit-the-queryset-of-entries-displayed-for-a-django-admin-inline) instead. – piro Sep 12 '16 at 18:00