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,
querysetnot eliminate duplicate rows. in practice, problem, because simple queries suchblog.objects.all()don’t introduce possibility of duplicate result rows. however, if query spans multiple tables, it’s possible duplicate results whenquerysetevaluated. that’s when you’d usedistinct().
emphasis mine.
Comments
Post a Comment