将Postgres原始查询转换为Django Orm查询

时间:2018-08-05 08:41:25

标签: django join django-orm

我有一个带(user_id,total_points和total_time)字段的userpoints表。如果我想获得基于total_points和total_time的排名列表,我可以像

chartData

使用django orm可以做到

 SELECT *,
  dense_rank() OVER (
    ORDER BY total_points DESC, total_time ASC
  ) AS rank from userpoints

如果我想从中获取特定的user_id,我可以通过

 UserPoints.objects.annotate(
        rank=Window(
            expression=DenseRank(),
            order_by=[F('total_points').desc(),
                      F('total_time').asc()]))

我试图像那样

SELECT *,

 from ( SELECT *,
  dense_rank() OVER (
    ORDER BY total_points DESC, userpoints.total_time ASC
  ) AS rank from userpoints ) as u INNER JOIN userpoints on u.user_id = userpoints.user_id where userpoints.user_id='users_uuid'

但是我遇到了类似的错误

UserPoints.objects.select_related('user_id').get(
        user_id='query_user_id').annotate(
            rank=Window(
                expression=DenseRank(),
                order_by=[F('total_points').desc(),
                          F('total_time').asc()]))

如何使用django orm执行第二个查询?

0 个答案:

没有答案