I
I
Igor Lyutoev2015-02-03 11:32:34
Django
Igor Lyutoev, 2015-02-03 11:32:34

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('Дата проведения мероприятия')

The task is to display on the page a list of events for a certain date (show the time of the sessions) and break it into pages.
I went this way:
1. We select by the date of the event sessions - they are paginated.
2. Based on the selected events and date, sessions are selected and transferred to the template through the context. And there they are displayed through {% regroup %}.
But to make a selection of sessions taking into account pagination does not work.
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

Subsequently, it will be necessary to fasten the selection by the category of the event.
Tell me - maybe the logic is chosen incorrectly.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2015-04-12
@deliro

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 %}

Try:
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 question

Ask a Question

731 491 924 answers to any question