[英]Peewee ORM get similar entries based on foreign key
I'm having problem with writing query for getting similar posts in a blog based on tags they have. 我在编写查询以基于他们具有的标签在博客中获取相似帖子时遇到问题。 I have following models:
我有以下型号:
class Articles(BaseModel):
name = CharField()
...
class Tags(BaseModel):
name = CharField()
class ArticleTags(BaseModel):
article = ForeignKeyField(Articles, related_name = "articles")
tags = ForeignKeyField(Tags, related_name = "tags")
What i'd like to do is to get articles with similar tags sorted by amount of common tags. 我想做的是获取具有相似标签的文章,并按常见标签数量进行排序。
Edit 编辑
After 2 hours of fiddling with it i got the anwser i was looking for, i'm not sure if it's the most efficient way but it's working: 经过2个小时的摆弄之后,我得到了我一直在寻找的anwser,我不确定这是否是最有效的方法,但是它可以正常工作:
Here is the function if anyone might need that in the future: 如果有人将来需要,可以使用以下功能:
def get_similar_articles(self,common_tags = 1, limit = 3):
"""
Get 3 similar articles based on tag used
Minimum 1 common tags i required
"""
art = (ArticleTags.select(ArticleTags.tag)\
.join(Articles)\
.where(ArticleTags.article == self))
return Articles.select(Articles, ArticleTags)\
.join(ArticleTags)\
.where((ArticleTags.article != self) & (ArticleTags.tag << art))\
.group_by(Articles)\
.having(fn.Count(ArticleTags.id) >= common_tags)\
.order_by(fn.Count(Articles.id).desc())\
.limit(limit)
Just a stylistic nit, table names (and model classes) should preferably be singular. 只是样式上的细小,表名(和模型类)最好是单数。
# Articles tagged with 'tag1'
Articles.select().join(ArticleTags).join(Tags).where(Tags.name == 'tag1')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.