gpt4 book ai didi

python-3.x - Sqlalchemy 从关系中获取数据

转载 作者:行者123 更新时间:2023-12-04 10:42:45 27 4
gpt4 key购买 nike

我有这个模型

class Post(Base):
__tablename__ = 'posts'
id = Column(Integer, primary_key=True)
content = Column(Text)
author = Column(Integer, ForeignKey('users.id'))
to_topic = Column(Integer, ForeignKey('topics.id'))

def __init__(self, content: str, author: int, to_topic: int) -> None:
self.content = content
self.author = author
self.to_topic = to_topic

class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
username = Column(String(30))
email = Column(String(40))
password = Column(String(255))
registred_at = Column(DateTime, default=datetime.datetime.now)
last_logged_in = Column(DateTime)
last_login_attempt = Column(DateTime)
avatar = Column(Integer, ForeignKey('files.id'))
role = Column(String(20))
email_confirm = Column(Boolean, default=False)
children_forum = relationship('Forum')
children_topic = relationship('Topic')
children_post = relationship('Post')

我正在尝试获取将包含 Post.content、Post.author.username 的查询,但我如何在 session 中执行此操作?

我试过了

 posts = db_session.query(Post, User).filter(
Post.to_topic == topic_id).with_entities(Post.content, Post.author.username)

但这不起作用,因为作者只是整数 (id),所以我希望我需要以某种方式在一个查询中获取作者对象和发布对象,但我不知道如何获取。在 sql 中,只需 2 个查询就很容易,但在这里我不知道它是如何完成的。

最佳答案

 query_results = db_session.query(Post, User).\
join(User, Post.author == User.id).\
filter(
Post.to_topic == topic_id
).all()

我从未使用过 with_entities,但我知道这会给你一个元组列表,其中 query_results[0] 是你的 Post 实例,而 query_results[1] 将是您的 User 实例。

编辑:我相信您不必包含 Post.author == User.id 位,但如果您明确加入,它会更清晰。

关于python-3.x - Sqlalchemy 从关系中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59849952/

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