Search code examples
djangodjango-class-based-viewsdjango-generic-views

Dynamically Changing a ListView (by day)


I have a ListView (generic CBV) of events. This ListView should dynamically update each day, so that "old" events (i.e. events that have already happened) are excluded from the context when a user visits the page.

I just noticed that this page is not actually behaving as expected (a server restart is required in order for the ListView to update). I have a suspicion that this is because I'm using the queryset method, and that I should be doing the processing earlier:

class EventDirectoryView(ListView):
    model = Event
    # Exclude objects that are expired
    queryset = Event.objects.exclude(deadline__lt=(date.today()-timedelta(1)))
    template_name = 'event-directory.html'

In order to achieve my desired outcome, what is the earliest I should be modifying the queryset so that it is run each time the page is loaded?


Solution

  • You should override the get_queryset() method:

    class EventDirectoryView(ListView):
        ...
        def get_queryset(self):
            return Event.objects.exclude(deadline__lt=(date.today()-timedelta(1)))