2024-05-19 06:47:00 发布
网友
我有一个带有标签的Post对象。我需要得到其他职位的查询集与特定职位交叉标签的数量排序
例如,有4个贴子带有下一个标签:
因此,如果main post是第一个,那么排序后的queryset应该是:
3,2,4
有没有办法用django ORM
我已经着手编写下一个函数:
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]
这看起来很吓人,但很管用
我已经着手编写下一个函数:
这看起来很吓人,但很管用
相关问题 更多 >
编程相关推荐