[英]How to limit top N of each group in Django ORM by using Postgres Window functions or Lateral Joins?
I have following Post
, Category
& PostScore
Model.我有以下
Post
、 Category
和PostScore
Model。
class Post(models.Model):
category = models.ForeignKey('Category', on_delete=models.SET_NULL, related_name='category_posts', limit_choices_to={'parent_category': None}, blank=True, null=True)
status = models.CharField(max_length=100, choices=STATUS_CHOICES, default='draft')
deleted_at = models.DateTimeField(null=True, blank=True)
...
...
class Category(models.Model):
title = models.CharField(max_length=100)
parent_category = models.ForeignKey('self', on_delete=models.SET_NULL,
related_name='sub_categories', null=True, blank=True,
limit_choices_to={'parent_category': None})
...
...
class PostScore(models.Model):
post = models.OneToOneField(Post, on_delete=models.CASCADE, related_name='post_score')
total_score = models.DecimalField(max_digits=8, decimal_places=5, default=0)
...
...
So what i want is to write a query which returns N
number of posts ( Posts ) of each distinct category ( Category ) sorted by post score (denoted by total_score column in PostScore model) in descending manner.所以我想要编写一个查询,它返回每个不同类别( Category )的
N
个帖子( Posts ),按帖子分数(由PostScore模型中的 total_score 列表示)以降序方式排序。 So that i have atmost N records of each category with highest post score.这样我每个类别的帖子得分最高的 N 记录。
So i can achieve the above mentioned thing by the following raw query which gives me top 10 posts having highest score of each category:因此,我可以通过以下原始查询来实现上述目标,该查询为我提供了每个类别得分最高的前 10 个帖子:
SELECT *
FROM (
SELECT *,
RANK() OVER (PARTITION BY "post"."category_id"
ORDER BY "postscore"."total_score" DESC) AS "rank"
FROM
"post"
LEFT OUTER JOIN
"postscore"
ON
("post"."id" = "postscore"."post_id")
WHERE
("post"."deleted_at" IS NULL AND "post"."status" = 'accepted')
ORDER BY
"postscore"."total_score"
DESC
) final_posts
WHERE
rank <= 10
What i have achieved so far using Django ORM:到目前为止,我使用 Django ORM 所取得的成就:
>>> from django.db.models.expressions import Window
>>> from django.db.models.functions import Rank
>>> from django.db.models import F
>>> posts = Post.objects.annotate(
rank=Window( expression=Rank(),
order_by=F('post_score__total_score').desc(),
partition_by[F('category_id')]
)). \
filter(status='accepted', deleted_at__isnull=True). \
order_by('-post_score__total_score')
which roughly evaluates to大致评估为
>>> print(posts.query)
>>> SELECT *,
RANK() OVER (PARTITION BY "post"."category_id"
ORDER BY "postscore"."total_score" DESC) AS "rank"
FROM
"post"
LEFT OUTER JOIN
"postscore"
ON
("post"."id" = "postscore"."post_id")
WHERE
("post"."deleted_at" IS NULL AND "post"."status" = 'accepted')
ORDER BY
"postscore"."total_score"
DESC
So basically what is missing that i need to limit each group (ie category) results by using “rank” alias.所以基本上我需要通过使用“排名”别名来限制每个组(即类别)结果的缺失。
Would love to know how this can be done?想知道如何做到这一点?
I have seen one answer suggested by Alexandr on this question , one way of achieving this is by using Subquery and in operator.我已经看到Alexandr在这个问题上提出的一个答案,实现此目的的一种方法是使用Subquery和in运算符。 Although it satisfies the above condition and outputs the right results but the query is very slow.
虽然它满足上述条件并输出正确的结果,但查询速度很慢。
Anyway this would be the query if I go by Alexandr suggestions:无论如何,如果我 go by Alexandr 建议,这将是一个查询:
>>> from django.db.models import OuterRef, Subquery
>>> q = Post.objects.filter(status='accepted', deleted_at__isnull=True,
category=OuterRef('category')).order_by('-post_score__total_score')[:10]
>>> posts = Post.objects.filter(id__in=Subquery(q.values('id')))
So i am more keen in completing the above raw query (which is almost done just misses the limit part) by using window function in ORM.所以我更热衷于通过在 ORM 中使用window function 来完成上述原始查询(几乎完成了,只是错过了限制部分) 。 Also, i think this can be achieved by using lateral join so answers in this direction are also welcomed.
另外,我认为这可以通过使用横向连接来实现,因此也欢迎这个方向的答案。
So I have got a workaround using RawQuerySet but the things is it returns a django.db.models.query.RawQuerySet
which won't support methods like filter, exclude etc.所以我有一个使用RawQuerySet的解决方法,但问题是它返回一个
django.db.models.query.RawQuerySet
,它不支持过滤、排除等方法。
>>> posts = Post.objects.annotate(rank=Window(expression=Rank(),
order_by=F('post_score__total_score').desc(),
partition_by=[F('category_id')])).filter(status='accepted',
deleted_at__isnull=True)
>>> sql, params = posts.query.sql_with_params()
>>> posts = Post.objects.raw(""" SELECT * FROM ({}) final_posts WHERE
rank <= %s""".format(sql),[*params, 10],)
I'll wait for the answers which provides a solution which returns a QuerySet object instead, otherwise i have to do by this way only.我将等待提供解决方案的答案,该解决方案返回QuerySet object ,否则我只能这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.