Home > Back-end >  Returning a scalar from a Django function
Returning a scalar from a Django function

Time:11-12

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:

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")

CodePudding user response:

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']
  • Related