Search code examples
pythondjangodjango-filter

Django, How can i count how much student every group?


i can not filter my models ,for example i need show in result, please help, thank you

  1. date group 110 students 23
  2. date group 111 students 9

models

class Group(models.Model):
    title     = models.CharField(max_length=200, default=0)
    date_pub  = models.DateTimeField(auto_now_add=True)
    completed = models.BooleanField(default=False)

    def __str__(self):
        return self.title

    def datepublished(self):
        return self.date_pub.strftime('%d.%m.%Y')

class Student(models.Model):
    user      = models.OneToOneField(User, on_delete=models.CASCADE)
    group     = models.ForeignKey(Group,on_delete=models.CASCADE,default=0)
    rating    = models.CharField(default='5', max_length=200)
    date_pub  = models.DateTimeField(auto_now_add=True)
    completed = models.BooleanField(default=False)

    def __str__(self):
        return self.user.username

views

def groups(request):
    groups = Group.objects.all()
    context = {
        'groups': groups
    }
    return render(request, 'panel/panel_groups.html', context)

html

{% for i in groups %}
                <tr>
                  <td>{{ i.datepublished }}</td>
                  <td>{{ i.title }}</td>
                  <td>count</td>
                  <td>
                    <a href="{% url 'groups_detail'  i.id %}" class="btn btn-secondary">
                      <i class="fas fa-angle-double-right"></i> Details
                    </a>
                  </td>
                </tr>
              {% endfor %}

Solution

  • You can annotate the Groups with the number of students:

    from django.db.models import Count
    
    def groups(request):
        groups = Group.objects.annotate(nstud=Count('student'))
        context = {
            'groups': groups
        }
        return render(request, 'panel/panel_groups.html', context)

    In the template, you can then access the .nstud attribute of the Groups that arise from this queryset:

    {% for i in groups %}
     <tr>
        <td>{{ i.datepublished }}</td>
        <td>{{ i.title }}</td>
        <td>{{ i.nstud }}</td>
        <td>
          <a href="{% url 'groups_detail' i.id %}" class="btn btn-secondary">
            <i class="fas fa-angle-double-right"></i> Details
          </a>
        </td>
      </tr>
    {% endfor %}