CHOICES

22 views
Skip to first unread message

www.forum-gh.com

unread,
Jun 13, 2021, 6:04:58 AM6/13/21
to django...@googlegroups.com
Hello friends 
please i have: conversion_fqctor = models.charfield(choices=FACTOR)

i want to sum the conversion_factor inside my view.py how do i convert it to a decimal and use the Sum()

Sebastian Jung

unread,
Jun 13, 2021, 6:08:05 AM6/13/21
to django...@googlegroups.com
Hello,

i think this is the right answer:

from django.db.models import Sum

ModelName.objects.filter(field_name__isnull=True).aggregate(Sum('field_name'))
# returns {'field_name__sum': 1000} for example

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CALYpPT8_5sMsyjzvpdGZ3gBQbqiwQW7EHgZ61i4LdLQ1z38LYg%40mail.gmail.com.

Nikeet NA

unread,
Jun 13, 2021, 6:33:12 AM6/13/21
to Django users
from django.db.models import Sum, DecimalField
from django.db.models.functions import Cast

Model.objects.annotate(deci_con_factor=Cast('conversion_factor', DecimalField()).aggregate(sum=Sum('deci_con_factor')).get('sum')

You need to change your char type to decimal type , you can use CAST operator, you will cast you charfield to decimal field and annotate it on every object then use that annotated field in aggregate func. 
Reply all
Reply to author
Forward
0 new messages