Tuesday, August 30, 2016

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

Thanks Erik. Will try out the solution you mentioned.

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/2dc0eaa1-1c80-454d-9e3d-9ba4cbcb8140%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment