2 ms·
I like this: published_posts = Post.objects.filter(publish_date__gte=now()) post_count = published_posts.count() You can't just append a COUNT to an S
by StavrosK 10y ago
I like this:
published_posts = Post.objects.filter(publish_date__gte=now())
post_count = published_posts.count()
You can't just append a COUNT to an SQL query, you'd have to write two queries, or one query that returned both. The above code produces two different queries, so it's much more composable.
I use it for tacking on extra filtering terms as well:
if category:
published_posts = published_posts.filter(category=category)
- ZenoArrow 10y agoThis is simple in SQL. There are multiple ways of doing it. For example, using a GROUP BY... SELECT published_posts, COUNT(published_posts) FROM Table1 WHERE publish_date > '2017-02-20' GROUP BY published_posts
- StavrosK 10y agoThe above query generates SQL in the end. My point was that SQL is not composable, whereas the above is.