我遇到了一个我无法找到解释的问题.
给定一个对象(在本例中为“文章”),我想使用另一种类型的对象(在本例中为“类别”)来确定哪些其他文章与文章X最相似,如通过他们有共同的类别.文章和类别之间的关系是多对多的.用例是获取相关对象的快速列表以作为链接呈现.
我确切地知道如何手工编写SQL:
select
ac.article_id
from
Article_Category ac
where
ac.category_id in
(
select
category_id
from
Article_Category
where
article_id = 1 -- get all categories for article in question
)
and ac.article_id <> 1
group by
ac.article_id
order by
count(ac.category_id) desc, random() limit 5
我正在努力的是如何使用Django模型聚合来匹配这个逻辑,只运行一个查询.我是obv.如果可能的话,我更愿意在框架内完成.有没有人指点这个?
最佳答案 现在我已经在模型框架中找到了一种方法来实现这一点.
related_article_list = Article.objects.filter(category=self.category.all())\
.exclude(id=self.id)
related_article_ids = related_article_list.values('id')\
.annotate(count=models.Count('id'))\
.order_by('-count','?')
在related_article_list部分中,将分别包含与2个或更多类别匹配的其他Article对象.因此,当使用注释来计数它们时,数字将是> 1,他们可以这样订购.