1👍
✅
You could get the number of students in a group like this:
group = ... # get a group
n_students = Student_Group.objects.filter(group=group).count()
Then since every Student_Group object has one student, n_students
will contain the number of student in the given group.
To send this number to your template you can add it in your context:
def group_list(request):
groups = Group.objects.all()
return render(request, 'groups/group_list.html', {'groups': groups, 'n_students': n_students})
You could also see docs for ManyToMany
relationships, that could be helpful here.
EDIT
Take some time to check Python’s naming conventions; your Student_Group
should be StudentGroup
.
You can create a method in your model to return the number of students in a group:
# models.py
class Group(models.Model):
# fields
@property
def get_students_qty(self):
return self.student_group_set.all().count()
# Try with self.studentgroup_set.all().count() if the line
# above does not work
then in your template:
{% for group in groups %}
<p>{{ group.group_name }}</p>
<p>{{ group.monitor }}</p>
<p>{{ group.get_students_qty }}</p>
{% endfor %}
Source:stackexchange.com