1

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')))
djvg
  • 11,722
  • 5
  • 72
  • 103
haojie
  • 593
  • 1
  • 7
  • 19

3 Answers3

2
from django.db.models.functions import Length
from django.db.models import Sum
User.objects.annotate(l=Length("username")).aggregate(Sum("l"))
ramwin
  • 5,803
  • 3
  • 27
  • 29
0

you can try use

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

Jack
  • 56
  • 5
0

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"))
haojie
  • 593
  • 1
  • 7
  • 19