2

我有以下Post, Category&PostScore模型。

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)
    ...
    ...

所以我想要编写一个查询,它返回每个不同类别(CategoryN )的帖子数(Posts ),按帖子分数(由PostScore模型中的 total_score 列表示)以降序方式排序。这样我每个类别的帖子得分最高的 N 记录。

因此,我可以通过以下原始查询来实现上述目标,该查询为我提供了每个类别得分最高的前 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

到目前为止,我使用 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')

大致评估为

>>> 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

所以基本上我需要通过使用“排名”别名来限制每个组(即类别)结果的缺失。

很想知道如何做到这一点?

我已经看到Alexandr在这个问题上提出的一个答案,实现此目的的一种方法是使用Subqueryin运算符。虽然它满足上述条件并输出正确的结果,但查询速度很慢。

无论如何,如果我通过 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')))

所以我更热衷于通过在 ORM 中使用窗口函数来完成上述原始查询(几乎完成只是错过限制部分) 。另外,我认为这可以通过使用横向连接来实现,因此也欢迎这个方向的答案。

4

1 回答 1

1

所以我有一个使用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],)

我将等待提供返回QuerySet 对象的解决方案的答案,否则我必须这样做。

于 2021-02-13T08:28:54.170 回答