python - 如何解决django中注释的sql解码错误

标签 python django database mongodb djongo

我正在使用 mangodb 数据库开发 django 框架。

CRUD 操作工作正常,但我遇到注释查询接收错误的问题:

djongo.sql2mongo.SQLDecodeError: FAILED SQL: SELECT "app_message"."type", SUM(CASE WHEN "app_message"."type" = %(0)s THEN %(1)s ELSE %(2)s END) AS "bot" FROM "app_message" GROUP BY "app_message"."type"  LIMIT 21
Params: ('Outbound', 1, 0)
Version: 1.2.38
Message.objects.values('type').\
            annotate(bot=Count(Case(When(type="Outbound", then='id'), default=Value(0),
                                    output_field=IntegerField()),
                               ))

也尝试过版本 1.2.31,但没有成功。

Python版本:3.6.1, Django版本:2.2.7

最佳答案

以这种方式计数是没有意义的,因为 Value(0) 也将被计为 1。此外,你不需要自己过滤,Django 有办法在聚合函数中进行过滤,通过使用 filter=… parameter [Django-doc] :

from django.db.models import Count, Q

Message.objects.values('type').annotate(
    bot=Count('id'<b>, filter=Q(type='Outbound')</b>)
)

关于python - 如何解决django中注释的sql解码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59966064/

相关文章:

python - 将图像背景颜色更改为白色?

具有相同名称的 Django 模板标签

mysql - 从 MySQL 表中选择最后 20 个最新的唯一 URL

Python 多重处理不是按项目执行,而是按字符执行

python - 通过 Python 请求重用 Django 中的连接

python - python 的 random.shuffle 是否保证元素的顺序不同?

django - 在 django-rest-framework 中使用 .to_representation() 和 .to_internal_value?

mysql - 如何在带有django的mysql中的两个不同模式中使用同名的两个表

database - Solandra/Elastic Search - 全文搜索(使用 Cassandra)

PHP插入到mysql