Mohit Harshan
Mohit Harshan

Reputation: 1986

filter by count of reverse lookup

I have two models, for example,

class Student(models.Model):
    name = models.CharField(max_length=160)
    teams = models.ManyToManyField("Team", related_name="student", blank=True)

class Team(models.Model):
    name = models.CharField(max_length=160)

I want to retrieve all the teams which is not assigned to any student , ie all teams where students.count() is 0. How can i query this?

I have tried

   Team.objects.filter(student=None)

Upvotes: 0

Views: 32

Answers (1)

JPG
JPG

Reputation: 88499

Use isnull filter

Team.objects.filter(student__isnull=True)

Upvotes: 1

Related Questions