Django Querysets - 添加字符串文字注释

Ted*_*Ted 4 django django-orm django-queryset

我想从字面上将字符串添加到查询集对象。为什么,因为我将它发送到 JSON,将信息放在那里并使其可用而无需遍历查询集将其转换为自定义字典,这将非常好和干净。

我现在所拥有的:

a_vote_set.aggregate(
                    count = Count('id'),
                    avg=Avg('score'),
                    std=StdDev('score'),
                    sum=Sum('score'),
                )
Run Code Online (Sandbox Code Playgroud)

这让我明白:

{"count": 1, "std": 0.0, "sum": -4.0, "avg": -4.0}
Run Code Online (Sandbox Code Playgroud)

我想得到的是:

{"count": 1, "std": 0.0, "sum": -4.0, "avg": -4.0, "additional_value": "name of candidate"}
Run Code Online (Sandbox Code Playgroud)

我很想通过调用这样的东西来获得它:

    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),
                 )
Run Code Online (Sandbox Code Playgroud)

关于这是否可能的任何想法?

Gag*_*aro 10

您可以使用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()),
)
Run Code Online (Sandbox Code Playgroud)

  • 我认为这只有在模型具有字段 `additional_value` 时才有效,否则你会得到 `FieldError: Cannot resolve expression type, unknown output_field` (6认同)

Nad*_*seo -1

您也许可以使用.extra() ,例如:

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']
                )
Run Code Online (Sandbox Code Playgroud)

您也许还可以将 Q() 和 F() 值传递到选择中,但我不确定。