Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I tried to sum the data from my database using the below code.

models.py

class Income(models.Model):

    Total= models.CharField(max_length=512,null =True,blank=True)

views.py :

Total_income = Income.objects.filter(Q(title='Salary')| Q(title='Bonus')).aggregate(Sum('Total'))

But I am getting an error when I try to run it.

('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Operand data type nvarchar is invalid for sum operator. (8117) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)')

1 Answer

0 votes
by (36.8k points)

You are trying to SUM CharField, not Integer, that's why you see the error. So you need to make that field integer, or if for any reason you need it to left as CharField:

from django.db.models.functions import Cast

Income.objects.filter(

    Q(title='Salary')| Q(title='Bonus')

).annotate(

    total_as_float=Cast('Total', FloatField()

).aggregate(Sum('total_as_float'))

 If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch

Browse Categories

...