Peewee:通过多对多关系过滤

时间:2015-12-16 10:33:38

标签: python orm peewee

这是一个基本示例 - 帖子由用户拥有和喜欢。如何为特定用户选择喜欢的帖子?

import datetime
import peewee

class User(peewee.Model):
    name = peewee.CharField(max_length=200)

class Post(peewee.Model):
    user = peewee.ForeignKeyField(User)
    text = peewee.TextField()

class Like(peewee.Model):
    user = peewee.ForeignKeyField(User)
    post = peewee.ForeignKeyField(Post)
    time = peewee.DateTimeField(default=datetime.datetime.now)

我从Like模型的角度进行查询,使用Like.select()开始查询并加入Post模型。好吗?我如何从Post模型的角度进行查询,即Post.select()...

以下是一个充满便利的完整示例:

def check_likes():
    user, _ = User.get_or_create(name="John")
    post, _ = Post.get_or_create(text="Hello world!", user=user)
    like, _ = Like.get_or_create(post=post, user=user)

    print("Created: ", user, post, like)

    # Get liked posts for user
    query_likes = (Like.select()
        .where(Like.user == user)
        .join(User)
        .join(Post))
    liked_posts = [like.post for like in query_likes]

    print("Liked posts: ", liked_posts)

if __name__ == '__main__':
    User.create_table(True)
    Post.create_table(True)
    Like.create_table(True)

    check_likes()

UPD。我现在最终得到了这样的询问:

def liked_by(user_id):
    """Active posts liked by user."""
    return (Post.select(Post, User, Like)
        .join(User, on=(Post.user == User.id))
        .switch(Post)
        .join(Like, peewee.JOIN.LEFT_OUTER,
              on=(Like.post == Post.id).alias('like'))
        .where(Like.user == user_id)
        .order_by(Like.time.desc()))

1 个答案:

答案 0 :(得分:1)

上面的查询应该有效,但您可以将其修改为:

Like.select(Like, Post)...

您还需要注意如何加入表格。使用'开关'方法:

query_likes = (Like.select(Like, Post)  # <<< Add like and post
    .where(Like.user == user)
    .join(User)
    .switch(Like)  # <<< You need this.
    .join(Post))
liked_posts = [like.post for like in query_likes]

你也可以这样做:

Post.select().join(Like).where(Like.user == some_user)