下面的代码写在flask框架的views.py中:
view.py:
motions = db.session.query(
Motion.id,
Motion.summary,
Motion.motion_type_id,
Motion_Type.description,
Motion_Type.id,
Motion.mp_op_type,
Motion.judge_id,
Judge.id,
Judge.name,
Motion.case_id,
Case.id,
Case.summary,
Case.case_type_id,
Case_Type.description,
Case_Type.id,
Motion.ruling_id,
Ruling.name,
Ruling.id
).filter(
Case.id == Motion.case_id
).order_by(
Judge.name,
Case_Type.description,
Ruling.name,
Motion_Type.description
)
如何在查询中获取属性?我想得到类似的东西:
for x in motions:
print(x.ruling())
但是,我的错误是在views.py的“动作”中没有名为“统治”的属性。所以我的问题是,如何在查询中获取属性?我是否缺少某些东西,或者喜欢,我应该从models.py调用某些东西还是在html模板上实例化某些东西?非常困惑。
答案 0 :(得分:0)
问题是您并未真正使用设计的Query API。似乎您正在寻找这样的东西(假设您的关系在模型中已正确设置):
import sqlalchemy as sa
motions_query = db.session.query(
Motion
).join(
Motion.case
).join(
Case.judge
).join(
Case.case_type
).options(
sa.orm.contains_eager(Motion.case).contains_eager(Case.judge),
sa.orm.contains_eager(Case.case_type)
).filter(
Case.id == Motion.case_id
).order_by(
Judge.name,
Case_Type.description,
Ruling.name,
Motion_Type.description
)
for motion in motions_query:
print(motion.case.summary)
print(motion.case.judge.name)