小编tbo*_*203的帖子

注释查询集是否存在匹配的相关对象

我有两个具有显式多对多关系的模型:事物,auth.user和连接这两者的“收藏夹”模型。我希望能够通过“事物”是否被特定用户喜欢来订购它们。在Sqlite3中,我提出的最佳查询是(大致)如下:

select 
    *, max(u.name = "john cleese") as favorited 
    from thing as t 
        join favorite as f on f.thing_id = t.id 
        join user as u on f.user_id = u.id
    group by t.id
    order by favorited desc
    ;
Run Code Online (Sandbox Code Playgroud)

在sql-to-django转换中让我绊倒的是一max(u.name = "john cleese")点点。据我所知,Django支持算术运算,但不支持相等运算。我能找到的最接近的是一个case语句,它不能正确地对输出行进行分组:

Thing.objects.annotate(favorited=Case(
    When(favorites__user=john_cleese, then=Value(True)),
    default=Value(False),
    output_field=BooleanField()
))
Run Code Online (Sandbox Code Playgroud)

我尝试过的另一个方向是使用RawSQL

Thing.objects.annotate(favorited=RawSQL('"auth_user"."username" = "%s"', ["john cleese"]))
Run Code Online (Sandbox Code Playgroud)

但是,这是行不通的,因为(据我所知)没有办法显式联接所需的favoriteand auth_user表。

有什么我想念的吗?

django django-queryset

2
推荐指数
1
解决办法
1103
查看次数

标签 统计

django ×1

django-queryset ×1