> Hi all,
>
> I have models called Books.
>
> To get unique results from Books, usually I use order_by().values('field').
> For example, I want unique writter :
>
> Books.objects.filter(created__year=2012).order_by('writter').values('writter').distinct()
>
> But, how to get unique results from sliced Queryset ?
>
> books = Books.objects.filter(created__year=2012)[:5]
>
> # Doesnt' works , Can reorder a query once a slice has been taken
> unique = books.order_by('writter').values('writter').distinct()
>
> # Doesnt' works, it will show all queryset (not unique)
> unique = books.values('writter').distinct()
>
> # Also doesn't works
> unique = books.annotate().values('writter').distinct()
> unique = books.values('writter').distinct().annotate().
>
> Anyone have this problem ? Is it possible to get unique results from
> sliced queryset ?
I am afraid that using Django ORM this is not possible. The reason is,
the real SQL query would look something like:
select distinct writer from (
select writer from books where year = 2012 order by writer limit 5
);
And Django ORM just can't do that query for you. You might want to do
a raw SQL query, or just do the "distinct" step in Python, which is
probably the easiest solution (set() is your friend here).
Of course, if you want the first 5 distinct writers, thats easy to do.
But getting the distinct writer values in the 5 first rows is harder
to do.
- Anssi
--
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+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
No comments:
Post a Comment