将原始sql查询转换为具有多个连接的django orm

rnmwe5a2  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(262)

我需要用django的orm重写这个原始查询:

SELECT count(u.username) as user_count, l.id as level_id, l.name as level_name
FROM users u
JOIN user_levels ul ON ul.username = u.username
JOIN sub_levels sl ON sl.id = ul.current_sub_level_id
JOIN levels l ON l.id = sl.level_id
WHERE u.created_at::DATE >= '2018-01-01' AND u.created_at::DATE <= '2018-01-17' AND u.type = 'u'
GROUP BY l.id, l.name

到目前为止,我可以这样写:

Users.objects.select_related('user_levels', 'sub_levels', 'levels')
.filter(created_at__date__gte='2018-01-01', created_at__date__lte='2018-01-17', type='u')
.values('userlevel__current_sub_level_id__level_id', 'userlevel__current_sub_level_id__level__name')
.annotate(user_count=Count('username'))

输出已完成 "userlevel__current_sub_level_id__level_id" 以及 "userlevel__current_sub_level_id__level__name" 柱。我要把他们化名为 "level_id" 以及 "level_name" .
我该怎么做?

cbeh67ev

cbeh67ev1#

在这种情况下,使用f()表达式是合适的。试试这个:

from django.db.models import F

Users.objects.select_related('user_levels', 'sub_levels', 'levels')
.filter(created_at__date__gte='2018-01-01', created_at__date__lte='2018-01-17', type='u')
.annotate(level_id=F('userlevel__current_sub_level_id__level_id'), level_name=F('userlevel__current_sub_level_id__level__name'))
.values('level_id', 'level_name')
.annotate(user_count=Count('username'))
ecfsfe2w

ecfsfe2w2#

你试过f()表达式吗?
你可以这样使用它。

from django.db.models import F

queryset.annotate(final_name=F('selected_name'))

有关更多信息,请查看此项。
别忘了用最后的\名称更改值。

相关问题