简体   繁体   English

如何在 django 中获取 model 对象的计数

[英]How to get count of model objects in django

Would anyone try to explain to me why I can't get a count of what is the query.有人会尝试向我解释为什么我无法计算查询是什么。 I'd like to get count for all the books borrowed by every student我想统计每个学生借的所有书

def view_student(request):  
    issues = Student.objects.all()
    for issue in issues:
        borroweds = Issue.objects.filter(borrower_id__student_id = issue.student_id).count()
        print(borroweds)
    return render(request, 'view_student.html', {'borroweds':borroweds})

And the tml code is this. tml 代码是这样的。

{% for student in students %}
    <tr>
      <td>{{ forloop.counter }}</td>
      <td>{{ student.student_id }}</td>
      <td>{{ student.name }}</td>
      <td>{{ student.batch }}</td>
      <td>{{ student.semester }}</td>
      <td><a href="{% url 'all_borrowed' student.student_id %}"> {{ borroweds }}</a> </td>
     </tr>
  {% endfor %}

This gives me a list of all students with books borrowed print(borroweds)这给了我所有借书的学生名单print(borroweds)

while in the template {{ borroweds }} gives me 0 's Am I calling it the wrong way of the code in the views????而在模板中{{ borroweds }}给了我0我是否称它为视图中代码的错误方式????

class Student(models.Model):
    school = models.ForeignKey(School, on_delete=models.CASCADE)
    name = models.CharField(max_length=200)
student_id = models.CharField(max_length=20, unique=True)

class Issue(models.Model):
    borrower_id = models.ForeignKey(Student,on_delete=models.CASCADE)
    book_id = models.ForeignKey(Books,on_delete=models.CASCADE)
    issue_date = models.DateField(default=datetime.date.today)

You should be able to do something like this with Aggregation: Following relationships backwards你应该能够用聚合做这样的事情:向后跟踪关系

This will not work out of the box, I'm not sure how your models are designed.这不会开箱即用,我不确定您的模型是如何设计的。 If you post them I can help you further.如果您发布它们,我可以进一步帮助您。

If you customized this to your models it would add the field issue__count to every Student .如果您将此自定义到您的模型中,则会将字段issue__count添加到每个Student

from django.db.models import Count

def view_student(request): 
    students = Student.objects.annotate(Count('issue'))
    return render(request, 'view_student.html', {'students': students})

The problem is, every time you loop through the issues, you are re-declaring the borroweds variable.问题是,每次您遍历问题时,您都在重新声明借用变量。 Hence, when the loop ends, you are left with the number of books borrowed by the last person (ie the last issue instance of the issues queryset).因此,当循环结束时,您会得到最后一个人借的书的数量(即问题查询集的最后一个问题实例)。 That's why you are probably getting a zero.这就是为什么你可能得到一个零。

You're overriding borroweds at each iteration of your for loop.您在 for 循环的每次迭代中都覆盖borroweds的内容。 Don't iterate over a Django queryset, you usually don't need to do this.不要遍历 Django 查询集,通常不需要这样做。

Instead, use annotate and count.相反,请使用注释和计数。

from django.db.models import Count

def view_student(request):  
    students = Student.objects.annotate(borrowed_books=Count('issue'))
    return render(request, 'view_student.html', {'students':student})

And in your template, you can access it with:在您的模板中,您可以通过以下方式访问它:

{% for student in students %}
{{ student.borrowed_books }}
{% endfor %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM