distinct().filter() applies filter before distinct

23 views
Skip to first unread message

John Rambo

unread,
Jun 10, 2014, 5:06:50 PM6/10/14
to django...@googlegroups.com

If we chain a call to filter() after a call to distinct(), the filter is applied to the query before the distinct. How do I filter the results of a query after applying distinct?

Example.objects.order_by('a','b').distinct('a').filter(b='something)

The where clause in the SQL resulting from filter() means the filter is applied to the query before the distinct. I want to filter the queryset resulting from the distinct.

This is probably pretty easy, but I just can't quite figure it out and I can't find anything on it.

Another way to ask the question is how do I return a distinct QuerySet and then filter it?

John Rambo

unread,
Jun 10, 2014, 5:17:30 PM6/10/14
to django...@googlegroups.com
This better illustrates what I mean:

Example.objects.order_by('a','foreignkey__b').distinct('a').filter(foreignkey__b='something')

Derek

unread,
Jun 11, 2014, 10:01:26 AM6/11/14
to django...@googlegroups.com
It might be worth comparing the SQL that Django generates versus what you would write (or want to write) by hand:

MyModel.objects.all().query.sql_with_params()
Reply all
Reply to author
Forward
0 new messages