Python 如何向 Django QuerySet 添加附加列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25308828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:02:00  来源:igfitidea点击:

How to add additional column to Django QuerySet

pythonsqldjangodjango-models

提问by dev9

I have a QuerySet with Books and I would like to add a scorefield to every Book result.

我有一个带有 Books 的 QuerySet,我想score为每个 Book 结果添加一个字段。

qs = Book.objects.all()

In raw SQL I would write:

在原始 SQL 中,我会写:

SELECT
    *,
    (
        (SELECT COUNT(*) FROM votes WHERE value=1 AND book=b.id) - 
        (SELECT COUNT(*) FROM votes WHERE value=-1 AND book=b.id)
    ) AS score
FROM
    Book b;

How can I achieve it in Django? I tried annotate(), but it seems it's not meant for this kind of stuff.

我怎样才能在 Django 中实现它?我试过了annotate(),但它似乎不适合这种东西。

采纳答案by ambi

If votes possible values are only 1 and -1 you can just sum them using mentioned annotate: Book.objects.annotate(score=Sum('votes__value')).

如果投票可能的值只有 1 和 -1,您可以使用提到的annotate 将它们相加:Book.objects.annotate(score=Sum('votes__value'))

If there is more possible values you can filter annotation by adding .filter(votes__value__range=(1,1))to the above query.

如果有更多可能的值,您可以通过添加.filter(votes__value__range=(1,1))到上述查询来过滤注释。

If it's more complex you would have to use extrawith select.

如果它更复杂,则必须使用extrawith select

回答by Joseph

Raw SQL is notthe only way. You can use a Value()expression (see docs here):

原始 SQL不是唯一的方法。您可以使用Value()表达式(请参阅此处的文档):

from django.db.models import CharField, Value

MyModel.objects.all().annotate(mycolumn=Value('xxx', output_field=CharField()))