0

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
  • you mean {"school_name" : count } like this? if you want total students from all the schools all you have to do is Member count without any filter. Commented Aug 5, 2022 at 4:46

1 Answer 1

1

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

total_student = Members.filter(student__in=[1,5,8]).count()
Sign up to request clarification or add additional context in comments.

3 Comments

Although the name of the foreign key field is weird (student) the proper filter is student_id__in=(1, 5, 8)
@Benoît thank you for the correction, I changed the field name to student. There no different as the format of the list or tuple because in the document __in accepts multiple types In a given iterable; often a list, tuple, or queryset. Also don't have to specify _id because the default field for foreign key is the id
@LinhNguyen thank you so much. Appreciate your great help. It worked well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.