如何按特定对象的相交标记数排序查询集?

2024-05-19 06:47:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有标签的Post对象。我需要得到其他职位的查询集与特定职位交叉标签的数量排序

例如,有4个贴子带有下一个标签:

  1. 房子花园夏季
  2. 花园植物
  3. 夏季室内空调
  4. 游戏冬季雪球

因此,如果main post是第一个,那么排序后的queryset应该是:

3,2,4

有没有办法用django ORM


Tags: 对象游戏数量排序main职位标签post
1条回答
网友
1楼 · 发布于 2024-05-19 06:47:00

我已经着手编写下一个函数:

class Post(models.Model):
...
    def get_similar_posts(self, n_posts):
        posts_tagged_similarly = Post.objects.filter(tags__in=self.tags.all())
        other_posts = Post.objects.exclude(pk__in=posts_tagged_similarly)
        union = posts_tagged_similarly.exclude(pk=self.pk).annotate(n_tags=models.Count('tags')).\
            union(other_posts.annotate(n_tags=models.Value(0, models.IntegerField()))).order_by('-n_tags', '-published')
    return union[:n_posts]

这看起来很吓人,但很管用

相关问题 更多 >

    热门问题