Atma
Atma

Reputation: 29767

How to find a list of objects that do not have a relationship with another object in django

I have the following object structure:

class Customer(models.Model):
    name = models.CharField(max_length=128)

class Club(models.Model):
    customer = models.ForeignKey(Customer)


class ClubMember(models.Model):
    group = models.ForeignKey(Group)
    member = models.ForeignKey(Member)

class Member(models.Model):
    customer = models.ForeignKey(Customer)

How do I find all the members for a customer that do not yet have ClubMember objects created?

The result would be a queryset of members.

How can this be accomplished?

Upvotes: 1

Views: 58

Answers (2)

Peter DeGlopper
Peter DeGlopper

Reputation: 37319

If you're looking it up for a specific customer:

customer.member_set.filter(clubmember__isnull=True)

If you want all members that do not have ClubMember matches, regardless of customer:

Member.objects.filter(clubmember__isnull=True)

Upvotes: 3

Brent Washburne
Brent Washburne

Reputation: 13148

Maybe something like this:

Member.objects.attribute.exclude(id=clubmember_set__member_id)

Upvotes: 1

Related Questions