【发布时间】:2017-03-28 17:39:41
【问题描述】:
我有两个具有显式多对多关系的模型:一个东西,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
;
在我的 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()
))
我尝试过的另一个方向是使用RawSQL:
Thing.objects.annotate(favorited=RawSQL('"auth_user"."username" = "%s"', ["john cleese"]))
但是,这行不通,因为(据我所知)无法显式加入我需要的 favorite 和 auth_user 表。
我有什么遗漏吗?
【问题讨论】: