Django pagination in TemplateView?
Hello, I am trying to figure out how I can access multiple models in a Class View and paginate at the same time.
My Outcome after reading, DjangoDoc and Stackoverflow:
ListView
- I simply can use paginate_by=
but I can load only one Model.
TemplateView
- I can load many models but can not use paginate_by=
?
For example three Models: Chicken
, Cows
and Cats
(and I want to display on my page the last 3 entries of each model). All Models have a model field called entry date.
class HomeIndex(TemplateView):
template_name = 'home.html'
paginate_by = 3 # --- something like that
def get_context_data(self, **kwargs):
context = super(HomeIndex, self).get_context_data(**kwargs)
context['chickens'] = Chicken.objects.order_by('-entry_date'')
context['cows'] = Cows.objects.order_by('-entry_date'')
context['cats'] = Cats.objects.order_by('-entry_date')
return context
Or maybe I can add something to objects.order_by('-entry_date', < pagination? >)
.
Thanks
Django QuerySet has built-in results slicing.
Cows.objects.order_by('-entry_date'')[offset:limit]
For the last 3 entries, offset is 0 and the limit 3
Cows.objects.order_by('-entry_date'')[0:3]
or the same can be written in a more pythonic way
Cows.objects.order_by('-entry_date'')[:3]
To get last 3 cows, cats and chicken, following code will work.
def get_context_data(self, **kwargs):
context = super(HomeIndex, self).get_context_data(**kwargs)
context['chickens'] = Chicken.objects.order_by('-entry_date')[:3]
context['cows'] = Cows.objects.order_by('-entry_date')[:3]
context['cats'] = Cats.objects.order_by('-entry_date')[:3]
return context
References: