我有这个模特
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的查询,但是我该如何在会话中执行此操作?
我试过了
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
一点,但是如果您明确地加入联接,那么它会更加清晰。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句