Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Returning a scalar from a Django function

I have a silly question

I really want the below to return a single number, but it still returns an iterable object. Do you know how I can get it to return a scalar?

pts = skills.objects.filter(creator=request.user).raw('''SELECT sum(cast(points as int)) as id  FROM myapp_skills  WHERE status = 'closed' and creator = %s ''',[request.user.username])

Here is my skill model:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class skills(models.Model):
    skill_name = models.CharField(max_length=400, default="data")
    points = models.CharField(max_length=400, default="data")
    time_required = models.CharField(max_length=400, default="data")
    target_date = models.CharField(max_length=400, default='none')
    category = models.CharField(max_length=400, default="data")
    status =  models.CharField(max_length=400, default="data")
    skill_id =  models.CharField(max_length=400, default="data")
    creator = models.CharField(max_length=400, default="data")
    syllabus = models.CharField(max_length=40000, default="data")

>Solution :

You can make an ORM query which looks like:

from django.db.models import IntegerField, Sum
from django.db.models.functions import Cast

pts = skills.objects.filter(
    creator=request.user, status='closed'
).aggregate(
    total=Sum(Cast('points', output_field=IntegerField()))
)['total']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading