Skip to content

Instantly share code, notes, and snippets.

@ikedumancas
Created May 5, 2018 18:15
Show Gist options
  • Select an option

  • Save ikedumancas/6dada5dba45aeaaa88f0915d881dea6f to your computer and use it in GitHub Desktop.

Select an option

Save ikedumancas/6dada5dba45aeaaa88f0915d881dea6f to your computer and use it in GitHub Desktop.
Limit Inline query set shown in Admin
from .utils import LimitFormset
class LimitedInline(admin.TabularInline):
model = Limited
formset = LimitFormset
from django.forms.models import BaseInlineFormSet
class LimitFormset(BaseInlineFormSet):
def __init__(self, *args, **kwargs):
QUERYSET_LIMIT = 5
super(LimitFormset, self).__init__(*args, **kwargs)
# [::-1] reverses the queryset
self.queryset = self.queryset.order_by('-log_in')[:QUERYSET_LIMIT][::-1]
def get_queryset(self):
if not hasattr(self, '_queryset'):
# Override get_queryset to remove `if not qs.ordered:` check since we already ordered qs on init
if self.queryset is not None:
qs = self.queryset
else:
qs = self.model._default_manager.get_queryset()
self._queryset = qs
return self._queryset
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment