Home > Blockchain >  Django Queryset: Filter for subset of many to many relation
Django Queryset: Filter for subset of many to many relation

Time:12-23

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!

CodePudding user response:

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()

CodePudding user response:

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))
  • Related