简体   繁体   English

如何从 Django 模型中获取数据并进入 HTML 模板

[英]How to Get Data Out of a Django Model and in to the HTML Template

I have an AttendanceReport model where staff register information such as the feedback and the number of hours worked "nbr_heures"我有一个出勤报告模型,其中工作人员注册信息,例如反馈和工作小时数“nbr_heures”

My model:我的型号:

class AttendanceReport(models.Model):
    id=models.AutoField(primary_key=True)
    consultant_id=models.ForeignKey(Consultant,on_delete=models.DO_NOTHING)
    mission_id=models.ForeignKey(Mission,on_delete=models.CASCADE,null=True)
    session_year_id=models.ForeignKey(SessionYearModel,on_delete=models.CASCADE, null=True)
    nbr_heures = models.IntegerField(blank=False)
    feedback = models.TextField(max_length=255,null=True, default="")
    created_at=models.DateTimeField(auto_now_add=True)
    updated_at=models.DateTimeField(auto_now_add=True)
    objects=models.Manager()

I'm trying to the sum the values of 'nbr_heures' How can i properly do that ?我正在尝试对 'nbr_heures' 的值求和 我该如何正确地做到这一点? I tried this but its not working..我试过这个,但它不工作..

    hours_count=AttendanceReport.objects.annotate(nbr_heur=Sum('nbr_heures'))

Thank you in advance.先感谢您。

You need to .aggregate(…) [Django-doc] here:你需要.aggregate(…) [Django-doc]在这里:

hours_count = AttendanceReport.objects.aggregate(
    nbr_heur=Sum('nbr_heures')
)['nbr_heur']

An .aggregate(…) will sum all records in the queryset, whereas .annotate(…) [Django-doc] will perform an aggregate per object (or per unique values if you use .values(…) ). .aggregate(…)将对.aggregate(…)所有记录求和,而.annotate(…) [Django-doc]将对每个对象(或每个唯一值,如果您使用.values(…) )执行聚合。

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

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