Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding queryset for inline admin

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.

like image 737
contexter_patrick Avatar asked Apr 12 '13 16:04

contexter_patrick


Video Answer


1 Answers

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

like image 150
Komu Avatar answered Nov 16 '22 03:11

Komu