gpt4 book ai didi

python - Peewee:通过多对多关系进行过滤

转载 作者:行者123 更新时间:2023-11-30 23:02:50 25 4
gpt4 key购买 nike

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

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

最佳答案

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

Like.select(Like, Post)...

您还需要注意加入牌 table 的方式。使用“切换”方法:

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)

关于python - Peewee:通过多对多关系进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34309665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com