python - django 静态注解

标签 python django

我想使用 django 为数据库查询的结果添加一个静态值(因此不使用“原始”SQL)

例如,如果我有一个包含字段 make、model 和 color 的对象 Car,那么我希望我的结果集具有额外的静态值,看起来像这样:

make     model     color    sales
----     -----     -----    -----
nissan   bluebird  black    0
ford     fiesta    red      0
toyota   camry     green    0

我试过类似的代码

cars= Car.objects.all().annotate(sales=0)

但出现错误。我能做什么?

干杯, 戴夫

--Fedang #django 上的 Trindaz

最佳答案

Django 功能 Value expressions :

from django.db.models import Value

cars= Car.objects.annotate(sales=Value(0))

在 Django 3.2 之前,指定字段类:

from django.db.models import Value, IntegerField

cars= Car.objects.annotate(sales=Value(0, IntegerField())) 

您可以使用所有可用模型字段的实例来代替 IntegerField()(例如:CharField(),...)

关于python - django 静态注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3590306/

相关文章:

python - 一个用于 seaborn 热图子图的水平颜色条和带有 xticklabels 的 Annot Issue

python - 使用 % 进行 For 循环解析

django - South 处理模型 mixin 吗?

python - 按数据框中的位置扩展列

python - 我如何使用 HTTPResponseRedirect 对 django 消息进行单元测试?

python - 在 OrderedDict 中查找具有最小值的键

django - mysqlclient在mac os上的python3中安装

python - 使用 django 时消除 pylint 误报

python - 支持 slug 字段中的 unicode 字符

python - 如何访问本地网络上运行的服务器