Is there a way to specify (in an annotation or aggregation) that a sequence of F
expressions should be summed together without manually typing out F("first_prop") + F("second_prop") + ...
?
I want something similar to how python's sum()
function allows you to pass an iterable and get the sum of the values in the iterable i.e. sum([1,2,3])
returns 6
.
Concretely, I want something that looks like this:
class Tree(TimeStampedModel):
leaf_count = models.IntegerField()
branch_count = models.IntegerField()
Tree.objects.create(leaf_count=60, branch_count=8)
Tree.objects.create(leaf_count=30, branch_count=3)
# now I want to annotate a combined count using my imaginary IterableSum aggregator
combined_sums = list(
Tree.objects.all().annotate(
combined_count=IterableSum(fields=[F("leaf_count"), F("branch_count")])
).values_list("combined_count", flat=True)
)
combined_sums # [68, 33]
How can I achieve this?