[Django]-Function sum(boolean) does not exist

3👍

You may be able to do this with Sum, Case, When to count every time upvoters__upvote is True

pin.objects.annotate(
    num_of_upvotes=Sum(Case(
        When(upvoters__upvote=True, then=1),
        default=Value(0),
        output_field=IntegerField()
    ))
)

0👍

Postgres does not support SUMing boolean fields. You can use Cast to cast it to an integer:

pin.objects.annotate(
    num_of_upvotes=Sum(Cast(upvoters__upvote, output_field=IntegerField())),
)
👤Udi

Leave a comment