2

If I were to have two different QuerySets in Django, both representing a ManyToMany relation with the same model, how would I find the intersections?

veered
  • 618
  • 8
  • 19

3 Answers3

1

You might be able to avoid the question by using the IN operator to create a subquery: http://docs.djangoproject.com/en/dev/ref/models/querysets/#in

mlissner
  • 16,103
  • 17
  • 95
  • 162
0

Merge your querysets in a list and next, create a set, you'll convert back to a list :

from itertools import chain
merged_qs = chain(queryset1, queryset2) 
intersection_list = list(set(list( merged_qs )))
Pierre-Jean Coudert
  • 8,981
  • 10
  • 49
  • 59
0
  1. order querysets by same set of keys
  2. call iterator() on both querysets
  3. feed iterators to intersect function from this answer: Joining a set of ordered-integer yielding Python iterators
Community
  • 1
  • 1
Yaroslav
  • 2,678
  • 16
  • 16