[英]Django query expression for counting particular attendance
I have a field that has 1000 rows.我有一个有 1000 行的字段。 In these rows there are 2 status available.
在这些行中有 2 个状态可用。 Present and Absent.
存在与缺席。 I want to know if there's a query expression to count the total number of students present or absent from the Attendence field so that i can store the answers in the respective fields (Attendance field has been populated with 'Present' and 'Absent').
我想知道是否有一个查询表达式来计算出勤字段中存在或缺席的学生总数,以便我可以将答案存储在相应的字段中(出勤字段已填充“存在”和“缺席”)。
class StudentInClass(models.Model):
Attendance = models.CharField(max_length=20, default='None')
Total_Present = models.IntegerField
Total_Absent = models.IntegerField
I got it working with these commands but these are not what i exactly wanted.我让它使用这些命令,但这些不是我真正想要的。 If there is an expression query for this then please let me know.
如果对此有表达式查询,请告诉我。
present_count = StudentInClass.objects.filter(Attendance__contains='Present').count
absent_count = StudentInClass.objects.filter(Attendance__contains='Absent').count
you are looking for filter methods.您正在寻找过滤方法。 also I would have chosen BooleanField instead IntegerField.
我也会选择 BooleanField 而不是 IntegerField。 and then filter them and count.
然后过滤它们并计数。
class StudentInClass(models.Model):
attendance = models.CharField(max_length=20, default='None')
total_present = models.BooleanField(default=False)
total_absent = models.BooleanField(default=False,null=True)
student_count = StudentIntClass.objects.filter(total_present==True).count()
similar to this.与此类似。
Something like the below should work (not tested).像下面这样的东西应该可以工作(未经测试)。
from django.db.models.aggregates import Sum
StudentInClass.objects.aggregate(sum_present=Sum("Total_Present"), sum_absent=Sum("Total_Absent"))
I got it work with these commands but these are not what i exactly wanted.我可以使用这些命令,但这些并不是我真正想要的。 If there is an expression query for this then please let me know.
如果对此有表达式查询,请告诉我。
present_count = StudentInClass.objects.filter(Attendance__contains='Present').count absent_count = StudentInClass.objects.filter(Attendance__contains='Absent').count present_count = StudentInClass.objects.filter(Attendance__contains='Present').count Absent_count = StudentInClass.objects.filter(Attendance__contains='缺席').count
Probably you can use simple group by
:可能您可以使用简单
group by
:
from django.db.models import Count
StudentInClass.objects.values('Attendance').annotate(count=Count('Attendance'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.