Wednesday, October 19, 2022

Warning about filtering queryset in ClassBasedViews


class BookListView(ListView):
    model = Book
    queryset = Book.objects.filter(publication_date__lte=timezone.now())

I found that this code snippet to retrieve only books that has the publication date before today (assuming that could be books with publication date in the future) not work as I would expected. 

After some digging, I found that timezone.now() it's cached when server starts up (in a production environment), so this query filter by the date the server was started. So the solution is to use a dynamic filtering. 

Could be a good idea to include some warning about this in the documentation? I have tried to find some information but I did not find anything.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/e1604f4f-a00e-4302-9cfe-ab3c882b5645n%40googlegroups.com.

No comments:

Post a Comment