Ram Rachum
Ram Rachum

Reputation: 88598

Checking whether two Django querysets have any items in common

I have two querysetd in Django. How can I efficiently check whether they have any elements in common, i.e. if there exists any element that is in both querysets?

Upvotes: 3

Views: 1705

Answers (3)

Jose Cherian
Jose Cherian

Reputation: 7737

In Django 1.11, simply queryset1.intersection(queryset2)

Upvotes: 2

jproffitt
jproffitt

Reputation: 6355

You can use query sets like sets:

intersection = queryset1 & queryset2

intersection will be the intersection of the two querysets

Upvotes: 1

Amir Rachum
Amir Rachum

Reputation: 79645

You could check if an intersection exists:

(qs1 & qs2).exists()

Upvotes: 5

Related Questions