How to replace sum statement in Django sql statement with SUM query in django

created at 07-17-2021 views: 1

Introduction

I have a query similar to the following:

SELECT SUM(ISNULL(table.name)) FROM table

How to convert SUM to QuerySet in Django? (That is, why does the xyz conversion operate, such as MyModel.objects.xyz()?)

Solution

from django.db.models import Sum

ModelName.objects.filter(field_name__isnull=True).aggregate(Sum('field_name'))

How sum works:

ModelName.objects.aggregate(Sum('field_name'))
Please log in to leave a comment.