【问题标题】:Count field choices in a model?计算模型中的字段选择?
【发布时间】:2021-08-27 06:22:46
【问题描述】:

我是 django 的新手,我正在帮助创建一个网站,现在他们要求显示一个特定的数字,而我尝试使用 for 循环,它是这样的:

    class Students(models.Model):
...
section = (('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6'))
BlockNumber = models.CharField(max_length=10, choices=section)

现在我要做的是计算学生模型类中的每个部分选择。 我尝试使用下面的代码来计算每个选择:

def yearCount(request):
    year = Students.objects.all(Count('year'))
    blocks = Students.onjects.all(Count('section'))
    context = {'year': year,'blocks': blocks}
    return render(request, './chairperson/students/student_bsit1.html', context)

任何帮助将不胜感激,谢谢。

【问题讨论】:

  • count each section choice in the Students model class 你能详细说明一下吗...??您期望的样本结果是什么......??
  • 您是否要计算以 1 作为他们的部分、2 作为他们的部分等等的学生数量?如果是这样,请看这里:stackoverflow.com/questions/30752268/…

标签: django django-models


【解决方案1】:

如果您想计算您选择的特定行业的学生人数:

from django.db.models import Q, Count
student_counts = Students.objects.annotate(
    section1_count=Count('BlockNumber', filter=Q(BlockNumber='1')),
    section2_count=Count('BlockNumber', filter=Q(BlockNumber='2')),
    # section3_count... etc
)

您提到了您对 Django 的新认识,因此请参阅此处的一些关于代码样式的注释/提示,您的模型名称应该是复数。 Students 应该是 Student 并且您的字段应该是 block_number 而不是 BlockNumber。函数应该是year_count 而不是yearCountHere 是一篇提高代码可读性和可维护性的好文章。最好在您的编辑器上启动并运行一个 linter 以在项目的早期帮助解决这个问题,这样您就可以习惯 Python 样式指南。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-27
    • 2023-02-23
    • 1970-01-01
    • 2015-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多