python - Why does the Django filter() adds items instead of removing them? -


i'm curious filter() method behaviour. read in documentation can chained. ok let's try:

# returns queryset of 2 objects : [<cliprofile: sven>, <cliprofile: david>] res = someclass.objects.all()  # returns queryset of 3 objects : [<cliprofile: sven>, <cliprofile: sven>, <cliprofile: david>] res2 = res.filter(some_attr__gte=a_datetime_object)  

how possible? if initial queryset contains 2 objects, how possible filter() method makes queryset grow?

your filter applies related objects; <cliprofile: sven> 2 such objects matched, object listed twice.

add .distinct() call:

res2 = res.filter(some_attr__gte=a_datetime_object).distinct() 

as documentation .distinct() states:

by default, queryset not eliminate duplicate rows. in practice, problem, because simple queries such blog.objects.all() don’t introduce possibility of duplicate result rows. however, if query spans multiple tables, it’s possible duplicate results when queryset evaluated. that’s when you’d use distinct().

emphasis mine.


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -