Peewee ORM根据外键获取相似的条目

2024-04-19 07:54:14 发布

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

我在写基于标签的类似博客帖子时遇到了问题。我有以下型号:

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

我想做的是让文章与类似的标签排序的数量共同标签。你知道吗

编辑


经过两个小时的摆弄,我得到了我想要的答案,我不确定这是否是最有效的方法,但它的工作:

以下是将来可能需要的函数:

 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)

Tags: nameselftagarticletags标签commonarticles
1条回答
网友
1楼 · 发布于 2024-04-19 07:54:14

仅仅是一个风格上的nit,表名(和模型类)最好是单数的。你知道吗

# Articles tagged with 'tag1'
Articles.select().join(ArticleTags).join(Tags).where(Tags.name == 'tag1')

相关问题 更多 >