Ted
Ted

Reputation: 12318

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?

Upvotes: 8

Views: 13199

Answers (2)

Gagaro
Gagaro

Reputation: 782

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()),
)

Upvotes: 14

Naddiseo
Naddiseo

Reputation: 1034

You might be able to use .extra() something like:

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

                ).extra(
                       select={
                              'additional_value' : 'candidate_table.name' 
                              }, 
                       where=['candidate_table.id = vote_table.candidate_id']
                )

You may also be able to pass Q() and F() values into the select, but I'm not sure.

Upvotes: -1

Related Questions