Wednesday, August 31, 2016

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

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:

A.objects.filter(
b__in=B.objects
.annotate(max_date_created=Max('a__b__date_created'))
.filter(date_created=F('max_date_created'), text='ABCD')
)

Good luck,

Michal

--
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-users@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/20160831081747.GF6601%40koniiiik.org.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment