SQLAlchemy 两张表联表查询后获取两张表所有的字段

在实际开发中 发现 SQLAlchemy 中的一个问题

我想获得一张完整的连结表的结果

举个例子:

PostFollow 两个表格

Post 表格有 body 等列

Follow 表格有 follower_id 等列

在连结 PostFollow 的表后,对其查询

我希望获得的查询结果,能包含两个表格里的所有列,这样方便调用

data = Post.query.join(Follow,Follow.followed_id == Post.author_id).filter(Follow.follower_id == 2)

运行结果:

>>> data[0].body
'test body4'

>>>data[0].follower_id
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'Post' object has no attribute 'follower'

从上面看到查询结果是个 Post 对象,其不含 follower 列的信息

data = Follow.query.join(Post,Follow.followed_id == Post.author_id).filter(Follow.follower_id == 2)

运行结果:

>>> data[0].body
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'Follow' object has no attribute 'body'

>>> data[0].follower_id
2

同理,这次的 Follow 对象不含 body 列的信息

解决方案:

jijia2 模板中看到可以通过 .add_entity() 这种方式来访问,就想到是否在这里也是可以的,结果是可以的

data = Post.query.join(Follow,Follow.followed_id == Post.author_id)).add_entity(Follow).filter(Follow.follower_id == 2)
  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
SQLAlchemy中,可以使用join()方法实现多表联合查询。下面是一个简单的示例: 假设我们有两个:students和grades。students包含学生的姓名和ID,grades包含学生的ID和他们的成绩。 我们想要查询每个学生的姓名和他们的平均成绩,我们可以这样写: ```python from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, func from sqlalchemy.orm import sessionmaker, relationship from sqlalchemy.ext.declarative import declarative_base engine = create_engine('sqlite:///example.db') Base = declarative_base() class Student(Base): __tablename__ = 'students' id = Column(Integer, primary_key=True) name = Column(String) grades = relationship('Grade', backref='student') class Grade(Base): __tablename__ = 'grades' id = Column(Integer, primary_key=True) student_id = Column(Integer, ForeignKey('students.id')) score = Column(Integer) Session = sessionmaker(bind=engine) session = Session() # 使用join进行多表联合查询 query = session.query(Student.name, func.avg(Grade.score)).join(Grade).group_by(Student.name) for name, avg_score in query: print(name, avg_score) ``` 在上面的代码中,我们使用join()方法将Student与Grade联合查询。在join()方法中,我们传入了Grade作为参数,示要联合查询的。然后我们使用func.avg()函数求出每个学生的平均成绩,并使用group_by()方法按照学生姓名分组。最后,我们使用session.query()方法执行查询,并使用for循环遍历结果。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值