Tuesday, August 30, 2016

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

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.

Thanks.

On Tuesday, August 30, 2016 at 3:59:20 PM UTC+5:30, Erik Cederstrand wrote:

> Den 30. aug. 2016 kl. 11.20 skrev Erik Cederstrand <erik+...@cederstrand.dk>:
>
> I'm not even sure that's possible to express in SQL, but it would probably be quite convoluted if it is. Here's an easier-to-understand solution:
>
> res = set()
> for b in B.objects.all().select_related('a').annotate(Max('date_created')):
>    if b.date_created != b.date_created__max:
>        continue
>    if b.text != 'ABCD':
>        continue
>    res.add(a)

I did some more experimenting. I think this actually does what you want:

res = [
    b.a for b in B.objects
    .filter(date_created=Max('a__b__date_created'))
    .annotate(Max('a__b__date_created'))
    .filter(text='ABCD')
    .select_related('a')
]

which you can rewrite as:

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

Erik

--
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/13a40885-4cce-46af-ba50-368942608c37%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment