How to get unique results from fields in sliced QuerySet ?

1,326 views
Skip to first unread message

bash look

unread,
Feb 1, 2012, 3:24:13 AM2/1/12
to django...@googlegroups.com
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 ?


Thanks

Bashlook


akaariai

unread,
Feb 1, 2012, 8:14:58 AM2/1/12
to Django users
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

bash look

unread,
Feb 1, 2012, 10:59:58 AM2/1/12
to django...@googlegroups.com, akaariai
Thanks for share , Anssi.

I think the same way.
Hope another solution rather than sliced, like LIMIT options on QuerySet
in the future.

Using raw SQL can not be avoided at this cases.

Thanks anyway

Bash

Reply all
Reply to author
Forward
0 new messages