Wednesday, August 31, 2016

Re: A tricky query in one to many relationship - atleast for me:)

Hi Michal,

Thanks for the solution. I tried the solution in a different way:

A.objects.annotate( max_date_created=Max('b__date_created')).filter(b__date_created=F('max_date_created'), b__text='ABCD') 

Hope the above amounts to the same thing as you have suggested.


On Wednesday, August 31, 2016 at 1:48:38 PM UTC+5:30, Michal Petrucha wrote:
On Tue, Aug 30, 2016 at 11:46:14PM -0700, Web Architect wrote:
> Hi Erik,
> I tried your solution but there are some issues:
> .filter(date_created=Max('a__b__date_created'))  - this is throwing error
> saying not proper use of group function.
> If I remove the above, the result isn't correct where when I go through
> each 'a' in the result, associated latest B.text isn't always 'ABCD' - if
> there are multiple instances of B associated with an instance of A and one
> of the instances of B has text='ABCD' (might not be the latest
> date_created), that instance of B is also there in the query result.

Hmm, I haven't actually tried to run any code, but I'd try reordering
some of the method calls, and using an explcit field alias for the
annotation, which should let you then use an F() expression in
subsequent filters; something like this:

        .filter(date_created=F('max_date_created'), text='ABCD')

Good luck,


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
To post to this group, send email to
Visit this group at
To view this discussion on the web visit
For more options, visit

No comments:

Post a Comment