我有以下型号:
class business_member(base_model):
__tablename__ = "business_member"
id = Column(Integer, primary_key=True)
business_id = Column(Integer, ForeignKey("business.id"), nullable=False)
member_id = Column(Integer, ForeignKey("user.id"), nullable=False)
business_parts_id = Column(Integer, ForeignKey("business_parts.id"), nullable=False)
is_admin = Column(Boolean, nullable=True, default=False)
created_date = Column(DateTime, nullable=False)
modified_date = Column(DateTime, nullable=True)
__table_args__ = (UniqueConstraint("business_id", "member_id", name="business_member_uc"), )
business = relationship("business", back_populates="members")
member = relationship("user", back_populates="as_employee")
part = relationship("business_parts", back_populates="employees")
我转换了以下原始SQL:
SELECT id, member_id, is_admin FROM business_member WHERE id IN (
SELECT id FROM business WHERE business_id = (
SELECT business_id FROM business_member WHERE member_id = 5 and business_id = 1))
到SQLAlchemy查询:
session = database.get_session()
user_validation_query = session.query(business_member.business_id).filter_by(
member_id=kwargs["user_id"],
business_id=request.raw_args["business_id"]
).subquery()
get_business_id_query = session.query(business_member).options(
load_only(business_member.id)
).filter(business_member.business_id == user_validation_query).subquery()
member_list = session.query(business_member).filter(
business_member.id.in_(get_business_id_query)
).all()
一切正常,但我想在查询结果中返回id,is_admin和member(relationship)列,我尝试了不同的方法,如load_only()
,但没有一种方法正常工作。
我怎么能这样做??
更新
例如,我将查询更改为:
member_list = session.query(business_member).options(
load_only("id", "is_admin", "member")
).filter(
business_member.id.in_(get_business_id_query)
).all()
我得到以下异常:
can't locate strategy for (('deferred', False), ('instrument', True))
答案 0 :(得分:0)
使用此
member_list = session.query(business_member.id, business_member.is_admin, business_member.member).filter( business_member.id.in_(get_business_id_query)).all()