Warning in documentation about filtering queryset in ClassBasedViews

73 views
Skip to first unread message

Daniel Gayoso González

unread,
Oct 29, 2022, 9:02:39 AM10/29/22
to django-d...@googlegroups.com
Hello,

Following the example in https://docs.djangoproject.com/en/4.1/topics/class-based-views/generic-display/#viewing-subsets-of-objects I tried the following

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?

Thanks,
Daniel

David Sanders

unread,
Oct 29, 2022, 3:00:59 PM10/29/22
to django-d...@googlegroups.com
Hi Daniel,

I don't think a warning is necessary here as it's fairly standard Python.

To explain: the timezone.now() is evaluated at module level – ie only once when the Python module is imported – which explains the behaviour that you're experiencing.

If you like you can submit a documentation PR with some suggestions but others may also doubt the value of adding a warning given that the very next section explains how to do dynamic filtering. Personally I think by the time you get to advanced Django such as this, Python experience is assumed :)

Regards,
David

--
You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-develop...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-developers/CAHLCT5d3Dz3KTfpxhLQAUZjruhRLgb_XKbUKdv7VgHW_-VVfCg%40mail.gmail.com.

Adam Johnson

unread,
Oct 29, 2022, 6:38:50 PM10/29/22
to django-d...@googlegroups.com
I'm inclined to agree with David here. This is a “understanding Python” thing. We can’t feasibly add documentation warnings everywhere such a mistake could be made.

danig...@gmail.com

unread,
Oct 30, 2022, 7:30:33 AM10/30/22
to Django developers (Contributions to Django itself)
I thought that it would a good idea to point this because it is a bug that you will not catch until production stage, but I guess time dependant queries are prone to this and require experience.

After reading your comments I realize this is more a python problem than a Django one, as both of you said.

Thank you for your feedback on this
Reply all
Reply to author
Forward
0 new messages