Query for retrieving the latest of a related row.

12 views
Skip to first unread message

mli...@x76.eu

unread,
Aug 17, 2017, 2:48:03 PM8/17/17
to django...@googlegroups.com
Hi,
I have a Forum-table and a related Post-table.
In my "overview"-view I display a list of all the latest posts for each
forum.

My current solution goes something like this:

posts = []
for f in Forum.objects.all().order_by('name') :
posts += Post.objects.filter(forum=f).order_by('-posted').first()
# the 'posts' variable is pushed into the view context for display

Obviously this isn't optimal..
It would be more efficient if the above could be made into a single
query, but I can't figure out how.

I found some solutions through Google, but so far it is aggregations
using values() and Max() which doesn't allow me to return a query-set to
the list-view. (Or maybe it does, but I have yet to learn how).
So any pointers or hints are much appreciated.

I use Django 1.11 and sqlite.

Thanks.

Jani Tiainen

unread,
Aug 17, 2017, 3:26:28 PM8/17/17
to django...@googlegroups.com
Hi.

Actually your way is pretty much only way to do it.

With aggregation you can get latest post timestamp per forum but to get actual post requires second query. 

Also unless you list hundreds of forums per page performance shouldn't be a problem.

Note that you could use reverse relation to get posts per forum so you don't need to query Post model explicitly.

--
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 post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/0614bdd6-1a48-b8c0-305d-472cb9c7a8b9%40x76.eu.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages