Add single object(most recent) from foreign key relationship to django queryset

30 views
Skip to first unread message

Joshua Corlin

unread,
May 12, 2023, 3:03:56 PM5/12/23
to Django users
Hello Django Community, 

Im stuck on something that I feel should be pretty simple.  I have two models Request and RequestComment, naturally RequestComment foreign keys to Request. I have a scenario where i need to base some logic in a view related to Requests off of an attribute in the most recent RequestComment on a Request and im trying to see if I can add the most recent RequestComment for reach Request to a request queryset so that i can use this in a table.  

sample request queryset: 
q1 = Request.objects.filter("status="New", created_at__lt="timezone.now() - timdelta(days=1))

I would like to add the most recent comment object to each result this query, effectively adding the result of querying RequestComment for the related Request in each row of q1 and filtering by -created_at and calling .first() and adding that as like request_latest_comment or similar. Im looking to add the whole object, as RequestComment also foreign keys to user which i need some info there too.  

Is this something that can be done with annotate?  If someone is able to provide either a suggestion or a link to a kb/forum where similar has been done, id greatly appreciate it. 

Best, 
Josh

Andrew Kos

unread,
May 13, 2023, 4:41:53 PM5/13/23
to Django users

Could you do a separate query or use select_related() to retrieve the most recent comment then combine the two in your table building logic? You're going to be constrained by the structure of the models anyways and so will probably have to make a couple queries to the DB.
Reply all
Reply to author
Forward
0 new messages