Django Queryset: Filter for subset of many to many relation

Let's assume the following model:

class User(models.Model):
     clients = models.ManyToManyField(Client)   

How to query users by a list of clients, so that only those users are returned that have not other clients than those in the given list assigned.

User.objects.filter(client__??=[client1, client2])

I had a look at Django's documentation of field lookups, but that did not help.

Thanks in advance!

clients = [client1, client2]  # this is a list but most probably it will be a queryset, it works either way

users = []
for client in clients:
     users += client.users.all()

I think this needs to be done with sql EXCEPT which can be accessed by queryset.difference()

So the idea is take "ALL" Users and remove the ones that match your clients query.

User.objects.all().difference(User.objects.filter(clients__in=excluded_clients))
Back to Top