Reputation: 7743
In my django app (1.8) I have a model TeamMember
, which has a boolean field primary_contact
and a foreign key relationship to User
. I would like to find the set of User objects which have no related TeamMember
with primary_contact=True
. (TeamMembers
with primary_contact=False
are fine)
I can get the count of team members easily enough:
User.objects.annotate(teammember__count=Count('teammember'))
And I can prefetch primary_contact TeamMembers easily enough as well:
User.objects.prefetch_related(Prefetch('teammember_set', queryset=.objects.filter(primary_contact=True), to_attr='primary_contacts'))
However, I have not found the incantation allowing me to filter a queryset by "Users who have no primary_contact team members".
Obviously, I would like to do this in the ORM, minimizing queries, and without raw SQL if possible.
Upvotes: 0
Views: 255
Reputation: 25539
I might misunderstood your question but would this work?
User.objects.filter(Q(teammember__primary_contact=False) |
Q(teammember__isnull=True))
Upvotes: 1