On Mon, 2009-01-05 at 04:42 -0800, coan wrote:
> I have a model that looks something like this:
> 
> class Collection(models.Model):
>  user = models.ForeignKey(User)
>  item = models.ForeignKey(Items)
>  date = models.DateTimeField()
> 
> I'm trying to retrieve a list of unique users ordered by the last time
> they added something to their collection.
> I would expect this to work:
> distinct_users = User.objects.order_by('collection__date').distinct()[:
> 5]
> This query returns a list of users, but the users are not distinct.

There can be more than one date associated with a particular user, so
whilst the user + date combinations are all unique, the users on their
own may not be.

> How do I do this the right way?

Right now, with trunk or Django 1.0, it's not particularly easy without
using custom SQL or extra(). Without looking too hard at the details, I
suspect it's probably possible with the aggregates code that will be in
Django 1.1, though (it's currently on track to be merged into trunk in
about a week).

One practical solution is to use the result set you're getting now and
filter it further in Python. Or do a filter on the User table and use
extra(select=...., order_by=...) to also select the maximum creation
date for each user and order by that.

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

Reply via email to