On Thu, 2008-12-04 at 19:09 -0800, ryan wrote:
> For instance, I have two objects:
> 1) Blog
> 2) Entry with a ForeignKey to Blog, and a Date field titled DateAdded
> 
> Now, I want to list all my blogs, ordering by the most recent added
> entry.
> 
> I tried:
> blog.objects.all().sort_by('entry__dateAdded').distinct()
> 
> But the result was that is a given blog had more than 1 entry, then it
> shows up in the resulting queryset more than once. It appears distinct
> () is doing nothing in this case.

The distinct() call is working correctly (you're right that it is
effectively doing nothing, wrong to say it "doesn't work"). The problem
is that you are ordering by something that has multiple values and each
value contributes one output row. There is nothing in your ordering
statement to say that the database should only use the *maximum* value
of dateAdded for each entry. The only reasonable way to interpret
ordering by multi-valued fields is to treat each one as generating a
different output row, since otherwise we might as well just pick one at
random (the SQL specification agrees with that interpretation by the way
-- which is why Django does it. Only MySQL allows effective ordering by
columns not in the output list in this case and it's very non-standard).

Refer to the massive callout box in the documentation for distinct() for
a more SQL-specific explanation:
http://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct

You could achieve the effect you're after by using extra(select=...,
order_by=...) to select the maximum date added value as an extra
column. 

Alternatively (and this would require some fairly deep poking into Query
internals, so probably not recommended) you could add some extra stuff
to the where-clause to say "where dateAdded = (Select max(dateAdded)
from ...)". Possible some extra(where="....") usage could get you most
of the way there on that one.

Regards,
Malcolm



--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
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
-~----------~----~----~----~------~----~------~--~---

Reply via email to