我在用烧瓶炼金术和棉花糖。我这里描述了一个简单的一对多关系(一
Broker
可以有很多
Account
s) :
class Account(Base):
__tablename__ = 'accounts'
id = Column(Integer, primary_key=True)
broker_id = Column(Integer, ForeignKey('brokers.id'))
alias = Column(String)
# relationships
broker = relationship("Broker", back_populates="accounts", uselist=False)
class Broker(Model):
__tablename__ = 'brokers'
id = Column(Integer, primary_key=True)
name = Column(String)
# relationships
accounts = relationship("Account", back_populates="broker")
我的棉花糖模式定义如下:
class AccountSchema(ma.SQLAlchemyAutoSchema):
class Meta:
table = Account.__table__
sqla_session = db.session
account_schema = AccountSchema()
accounts_schema = AccountSchema(many=True)
class BrokerSchema(ma.SQLAlchemyAutoSchema):
class Meta:
table = Broker.__table__
sqla_session = db.session
accounts = ma.Nested(accounts_schema)
broker_schema = BrokerSchema()
brokers_schema = BrokerSchema(many=True)
我的
经纪人
路由可选择接受
broker_id
和
account_id
. 看起来是这样的:
@api.route("")
@api.route("/<int:broker_id>")
@api.route("/<int:broker_id>/accounts")
@api.route("/<int:broker_id>/accounts/<int:account_id>")
class BrokerResource(Resource):
def get(self, brokerage_id=None, account_id=None):
# construct query
query = ...
return {
"data": brokerages_schema.dump(query.all())
}
我想创建一个查询,该查询将返回适合使用
BrokerSchema
. 如果否
帐户\u id
已通过,则应返回所有子级
账户
物体。如果
帐户\u id
如果通过,则应返回单个记录。
如何构造这样的查询?