Search code examples
djangopostgresqldjango-ormdjango-databasedjango-annotate

PostgreSQL Programming error in Django Query


I have a query as below which returns the grade of all students of a specific class in a specific term(semester) in a specific session(academic year):

grades = Grade.objects.filter(term='First', student__in_class=1,session=1).order_by('-total')

then another query that annotate through the grades in order to get the sum of the 'total' field.

grades_ordered = grades.values('student')\
    .annotate(total_mark=Sum('total')) \
    .order_by('-total_mark')

At first everything works fine until when i migrated from using SQLite to postgreSQL then the following error begins to show up.

ERROR:

function sum(character varying) does not exist
LINE 1: SELECT "sms_grade"."student_id", SUM("sms_grade"."total") AS...
                                         ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

EDIT: here is my model

class Grade(models.Model):
    session = models.ForeignKey(Session, on_delete=models.CASCADE)
    term = models.CharField(choices=TERM, max_length=7)
    student = models.ForeignKey(Student, on_delete=models.CASCADE)
    subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
    fca = models.CharField(max_length=10)
    sca = models.CharField(max_length=10)
    exam = models.CharField(max_length=10)
    total = models.CharField(max_length=3, blank=True, null=True)
    grade = models.CharField(choices=GRADE, max_length=1, blank=True, null=True)
    remark = models.CharField(max_length=50, blank=True, null=True)

any help you can provide would be appreciated.

thanks


Solution

  • Store numbers in integer or decimal not in text/varchar field

    total = models.Integer(max_length=3, blank=True, null=True)
    

    see this link

    also read this