Django - How can I filter and count related objects of different ids

Viewed 34

Model 1:

class Member(models.Model):
    id = models.AutoField(primary_key=True)
    names = models.CharField(max_length=255, blank=True)
    student = models.ForeignKey('School', on_delete=CASCADE, null=True, 
    blank=True)

Model 2:

class School(models.Model):
    id = models.AutoField(primary_key=True)

I want to count the total students who are in different schools.

I tried total_student = Members.filter(school=1+5+8).count()but this is not working. Note: 1, 5 and 8 are the ids of the same type of schools in the school model which different members attend.

Please help me get this right.

1 Answers

Use the __in query filter of Django for filtering on multiple data per column:

total_student = Members.filter(student__in=[1,5,8]).count()
Related