Friday, September 9, 2011

Re: Trouble expressing a query in the ORM




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)

Let say I have two targets which I'll call target1 and target2.

Target1 have a property for yesterday and one for today. Target2 only have a property for yesterday. Both yesterday and today will be included in prop_dates since they are the latest for at least one target. And then Target1 will have two entries in properties while it should only have one for today.

I don't follow. The first instruction fetches all the Target objects, along with the latest Property related to each Target, and only selects those Properties' dates. You're saying Target1 has a Property A from yesterday, and B from today. Target 2 has a property C from yesterday. Only B and C's dates would be returned, not A's.

--
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/-/0oOvXPhajiwJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment