2

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
  • 1
    Have a look at the [aggregation](https://docs.djangoproject.com/en/3.0/topics/db/aggregation/#aggregation) section of the documentation. – Higor Rossato Jun 12 '20 at 07:07

4 Answers4

1

Probably you can use simple group by:

from django.db.models import Count

StudentInClass.objects.values('Attendance').annotate(count=Count('Attendance'))
ruddra
  • 50,746
  • 7
  • 78
  • 101
0

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.

ytsejam
  • 3,291
  • 7
  • 39
  • 69
0

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"))
Dušan Maďar
  • 9,269
  • 5
  • 49
  • 64
0

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