Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Querysets - add a string literal annotation

I want to literally add a string to a queryset object. Why, because I'm sending this to JSON and it would be so nice and clean to just put the information there and have it available without having to iterate over the queryset to turn it into a custom dictionary.

What I have now:

a_vote_set.aggregate(
                    count = Count('id'),
                    avg=Avg('score'),
                    std=StdDev('score'),
                    sum=Sum('score'),
                )

Which gets me this:

{"count": 1, "std": 0.0, "sum": -4.0, "avg": -4.0}

What I want to get is:

{"count": 1, "std": 0.0, "sum": -4.0, "avg": -4.0, "additional_value": "name of candidate"}

Which I would love to get by calling something like this:

    a_vote_set.aggregate(
                        count = Count('id'),
                        avg=Avg('score'),
                        std=StdDev('score'),
                        sum=Sum('score'),
                        additional_value=Literal(candidate.name),
                    )

or this:

    a_vote_set.aggregate(
                        count = Count('id'),
                        avg=Avg('score'),
                        std=StdDev('score'),
                        sum=Sum('score')
                 ).append(
                        additional_value=str(candidate.name),
                 )

Any ideas on if this is possible?

like image 767
Ted Avatar asked Jan 18 '23 20:01

Ted


1 Answers

You can add literal value with Value:

from django.db import models

a_vote_set.aggregate(
    count = Count('id'),
    avg=Avg('score'),
    std=StdDev('score'),
    sum=Sum('score')
).annotate(
    additional_value=models.Value(candidate.name, output_field=models.CharField()),
)
like image 137
Gagaro Avatar answered Jan 22 '23 15:01

Gagaro