[Answered ]-Django ORM "|" operator returning duplicate items

1👍

projects and subscribed_projects are two different many to many relations with Project, hence when one queries from them there are joins with different intermediate tables. Although I don’t know the exact internal working of the __or__ operator of a queryset, since you don’t get an error I can only assume that it will use the joins from both the tables in the combined query.

From the above analysis one can conclude that you end up joining over multiple tables, as it is obvious joins over multiple tables can easily introduce duplicate results. As you already know using distinct can solve this problem for you (won’t suggest using union because then it will limit the possible filters you can make on the unioned query):

queryset = me.projects.all() | me.subscribed_projects.all()
queryset = queryset.distinct()

Leave a comment