【问题标题】:Peewee ORM get similar entries based on foreign keyPeewee ORM 根据外键获取相似条目
【发布时间】:2014-03-22 05:15:21
【问题描述】:

我在编写查询以根据他们拥有的标签在博客中获取类似帖子时遇到问题。我有以下型号:

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

我想做的是让具有相似标签的文章按常见标签的数量排序。

编辑


摆弄了 2 个小时后,我得到了我正在寻找的答案,我不确定这是否是最有效的方法,但它正在工作:

如果将来有人可能需要,这里是这个功能:

 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)

【问题讨论】:

    标签: python peewee


    【解决方案1】:

    只是文体方面,表名(和模型类)最好是单数。

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

    【讨论】:

    • 但是如果在一篇文章中添加了4个标签怎么办,通过ArticleTags模型,我将如何选择具有最多同名标签的帖子。使用单个查询是否可行,例如this Stack overflow question。
    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 2018-07-19
    • 1970-01-01
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-09
    相关资源
    最近更新 更多