【问题标题】:Django Querysets - add a string literal annotationDjango Querysets - 添加字符串文字注释
【发布时间】:2012-02-05 16:29:00
【问题描述】:

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

我现在拥有的:

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

这让我明白了:

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

我想得到的是:

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

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

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

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

【问题讨论】:

    标签: django django-queryset django-orm


    【解决方案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']
                    )
    

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

    【讨论】:

    • DatabaseError: (1054, "Unknown column 'table.field' in 'field list'")
    • @est 你在说什么?
    • 好的,我通过添加tables=[]参数解决了这个问题。但结果不是内连接,而是像矩阵一样相乘。
    【解决方案2】:

    您可以使用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()),
    )
    

    【讨论】:

    • 我认为这只有在模型具有字段additional_value 时才有效,否则你会得到FieldError: Cannot resolve expression type, unknown output_field
    猜你喜欢
    • 2020-11-29
    • 2019-03-20
    • 2011-02-04
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    • 2011-08-27
    相关资源
    最近更新 更多