Tim Shaffer's response would have you doing N+1 queries, and having to loop
through all of your Target objects in-memory. Technically it would work, but
as soon as you have a decently sized amount of data in there it'd slow to a
crawl.
The best way I can see to do this straight with the Django ORM is:
prop_dates =
Target.objects.annotate(latest_property=Max('property__export_date')).values_list('latest_property',
flat=True)
properties = Property.objects.filter(export_date__in=prop_dates)
Which comes out to two queries. If you absolutely had to, you could execute
some raw SQL to narrow it down to one query. Please note that there is a
(very) small possibility that the second query might return extra Properties
for a given Target. Because it's operating based on date-timestamps, there
could be two Properties that happen to have the exact same export_date, one
of which happens to be the most recent for a given Target. Eliminating those
duplicates, if you want to account for that scenario, can be done in-memory
or I believe through some adjustments to the second line above.
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To view this discussion on the web visit
https://groups.google.com/d/msg/django-users/-/Hfzi77PqKukJ.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en.