1

我正在使用 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

4

2 回答 2

0

这是你可以做的:

from django.db.models import Q, Sum, IntegerField

Message.objects.values('type').annotate(
     bot=Sum(Case(When(type="Outbound", then=1), 
     default=0,output_field=IntegerField()))
)

希望这可以帮助!

于 2020-01-29T11:45:18.473 回答
0

以这种方式计数是没有意义的,因为 aValue(0)也将被视为一个。此外,您不需要自己过滤,Django 可以通过使用filter=…参数 [Django-doc]在聚合函数中进行过滤:

from django.db.models import Count, Q

Message.objects.values('type').annotate(
    bot=Count('id', filter=Q(type='Outbound'))
)
于 2020-01-29T11:30:01.137 回答