Richard Yang
Richard Yang

Reputation: 101

django, how to Use Count in Q

I have the following models:

class Group(models.Model):

    group_name = models.CharField(max_length=16)

class Member(models.Model):

    group = models.ForeignKey('Group')
    member_name = models.CharField(max_length=16)
    gender = models.BooleanField() #False is "female", True is "male"

How can I find a Group who has no Member, or where the number of male Members is zero?

I tried the following, but it didn't work:

Group.objects.filter( Q(member__isnull=True) |
                      Q(member__isnull=False) &
                      Q( Count(member__gender=True)=0 ) )

Upvotes: 2

Views: 743

Answers (1)

Sentient07
Sentient07

Reputation: 1290

Solution,

Group.objects.filter(Q(member__isnull=True) | ~Q(member__gender=True))

When you're trying to fetch something that might return multiple results, you should use filter and not get

If you want to count the query set, you can use,

Group.objects.filter(Q(member__gender=False )).count()

Upvotes: 2

Related Questions