Is it possible for Django to sum lengths of a non-numeric field?

Question:

I have learned we can sum all(or filtered) columns like price from this question.

ItemPrice.objects.aggregate(Sum('price'))

But is it possible for Django to sum non-numeric field’s length, such as CharField or JSONField? A pseudocode is like following.

User.objects.aggregate(Sum(len('username')))
Asked By: haojie

||

Answers:

from django.db.models.functions import Length
from django.db.models import Sum
User.objects.annotate(l=Length("username")).aggregate(Sum("l"))
Answered By: ramwin

you can try use

from django.db.models.functions import Length User.objects.aggregate(Sum(Length('username')))

Answered By: Jack

For a JSONFied, we can use Count to sum all the items.

from django.db.models import Sum, Count
User.objects.annotate(l=Count("json_filed")).aggregate(Sum("l"))
Answered By: haojie
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.