Django query expression for counting particular attendance

343 views Asked by At

I have a field that has 1000 rows. In these rows there are 2 status available. 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
4

There are 4 answers

1
ytsejam On

you are looking for filter methods. also I would have chosen BooleanField instead 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.

1
Dušan Maďar On

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"))
0
Syed Muhammad Ibrahim On

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

0
ruddra On

Probably you can use simple group by:

from django.db.models import Count

StudentInClass.objects.values('Attendance').annotate(count=Count('Attendance'))