Answer the question
In order to leave comments, you need to log in
How to make pagination in Django for one-to-many models?
I am making a poster application, There are the following models:
class Events(models.Model):
title = models.CharField('Название мероприятия', max_length=255)
class Session(models.Model):
event = models.ForeignKey(Events)
date = models.DateField('Дата проведения мероприятия')
class IndexView(generic.ListView):
template_name = 'events/list.html'
paginate_by = 1
def get_queryset(self, **kwargs):
date = datetime.today()
return Events.objects.filter(session__date=date).distinct()
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
date = datetime.today()
context['session'] = Session.objects.filter(event=self.get_paginate_by(self), date=date)
return context
Answer the question
In order to leave comments, you need to log in
model is not overridden.
get_queryset is hardcoded.
get_context_data is not needed (an object_list is sent to the template, moreover, only one).
{% for object in object_list %}
{% for session in object.session_set.all %}
{{ session }}
{% endfor %}
{% endfor %}
class IndexView(ListView):
template_name = 'events/list.html'
paginate_by = 1
model = Events
def get_queryset(self, *args, **kwargs):
return super().get_queryset(*args, **kwargs).filter(session__date=datetime.today()).distinct()
# Если python2, используйте super(IndexView, self) вместо super()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question