django - 如何使用 Django ORM 将注释字符串转换为 Bool

标签 django postgresql django-queryset django-orm django-annotate

我的问题如下。有一个请求

Thread.objects.all().annotate(is_marked=Count('mark', Q(mark__username='gou')))

在 SQL 中它看起来像这样

SELECT "api_thread"."id",
       "api_thread"."conference_id",
       "api_thread"."title",
       "api_thread"."description",
       "api_thread"."is_closed",
       "api_thread"."is_hidden",
       "api_thread"."is_pinned",
       "api_thread"."has_voting",
       "api_thread"."creator_uid",
       "api_thread"."created_at",
       "api_thread"."expired",
       COUNT("api_thread_mark"."user_id") FILTER (WHERE "auth_user"."username" = 'gou') AS "is_marked"
FROM "api_thread"
         LEFT OUTER JOIN "api_thread_mark" ON ("api_thread"."id" = "api_thread_mark"."thread_id")
         LEFT OUTER JOIN "auth_user" ON ("api_thread_mark"."user_id" = "auth_user"."id")
GROUP BY "api_thread"."id"

我需要做什么才能将数字转换为 bool 值。在 SQL 中它看起来像

COUNT("api_thread_mark"."user_id") FILTER (WHERE "auth_user"."username" = 'gou') > 0 AS "is_marked"

最佳答案

类似这样的吗?

from django.db.models import Case, When, Value, BooleanField, Count, Q

is_marked__count = Count('mark', Q(mark__username='gou'))
is_marked_bool = Case(When(is_marked__count__gt=0, then=Value(True)), default=Value(False), output_field=BooleanField())

Thread.objects.all().annotate(is_marked__count=is_marked__count).annotate(is_marked_bool=is_marked_bool

引用号:Conditional Expressions

关于django - 如何使用 Django ORM 将注释字符串转换为 Bool,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59408050/

相关文章:

Django 查询集 - 添加 HAVING 约束

python - django connection.queries - 'list' 对象不可调用

django - 在 Django 应用程序之间共享模型

html - 嵌入 YouTube 视频 - 拒绝在框架中显示,因为它将 'X-Frame-Options' 设置为 'SAMEORIGIN'

postgresql - Postgres bigserial 用完后怎么办?

python - 返回登录用户申请的所有职位的查询集

python - 如何将验证错误显示为 django admin 默认错误

sql - 仅当文本列不是数字时才添加新行

java - 需要插入数据库表

django - 如何使用现有字段之一的相同值但不同数据类型来注释 Django 查询集?