I have an existing system where I'm looking to limit the number of related object displayed in an admin inline.
For example, I have a model in the admin with an inline that can have up to thousands of related records. I'd like only display the most recent records (say the 5K most resent records). (Ideally, one would be able to paginate through inline records, but just limiting them would be sufficient for me.) I want to avoid the situation where an admin page loads with 60K inline records, which crashes the browser and taxes the server.
Based on the following SO question, I've created the following snippet: How to limit queryset/the records to view in Django admin site?
class TicketNoteAdmin(models.TabularInline):
model = models.TicketNote
def queryset(self, request):
qs = super(TicketNoteAdmin, self).queryset(request).order_by('-created')[:5000]
return qs
However, I get an "Cannot filter a query once a slice has been taken". I've even tried using a paginator, but get the same error.
from django.core.paginator import Paginator
class TicketNoteAdmin(models.TabularInline):
model = models.TicketNote
def queryset(self, request):
qs = super(TicketNoteAdmin, self).queryset(request).order_by('-created')
p = Paginator(qs, 5000)
page1 = p.page(1)
return page1.object_list
I understand why I am getting this error, but am wondering if there is a different approach that would allow me to restrict the number of inline objects displayed. Perhaps the admin wasn't designed to work with this many inline objects, but feel that there must be way to limit the admin inline record-set and prevent situations where the browser/server might crash because of too many inline objects. Any advice is much appreciated. Thank you for reading.
Try this:
from django.forms.models import BaseInlineFormSet
class TicketNoteFormSet(BaseInlineFormSet):
def get_queryset(self) :
qs = super(TicketNoteFormSet, self).get_queryset()
return qs[:5000]
class TicketNoteAdmin(models.TabularInline):
model = models.TicketNote
formset = TicketNoteFormSet
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