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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With