我将 Flask-SQLAlchemy 与 Flask-Marshmallow 一起使用,但我看到了我不理解的 Marshmallow 行为。
我有一个简单的多对一 SQLAlchemy,它工作得很好。关系的一侧是通过 LEFT OUTER JOIN 获取的。我的映射看起来像:
class Parent(db.Model):
__tablename__ = 'parents'
id = db.Column(db.Integer, primary_key=True)
child_id = db.Column(db.Integer, db.ForeignKey('children.id'))
child = db.relationship('Child', backref='parents', lazy='joined')
class Child(db.Model):
__tablename__ = 'children'
id = db.Column(db.Integer, primary_key=True)
到目前为止一切都很好,并且按我的预期加载。
但是当我用 Marshmallow 查询和序列化时,会执行一个 SELECT 来获取每个父母的孩子,尽管事实上孩子已经加载了。
def get_parents():
# use Flask's paginate() method
parents = Parent.query.paginate(1, 20, False)
# so far so good...LEFT OUTER JOIN is done...
# BOOM below!
return parent_paged_list_schema.dump(parents).data
为什么 Marshmallow 的序列化过程不直接使用内存中已经存在的孩子?
我肯定做错了什么。
以下是我的 Marshmallow 模式的外观供参考:
class ParentSchema(ma.ModelSchema):
id = fields.Integer()
child = fields.Nested(ChildSchema())
class Meta:
model = Parent
class ChildSchema(ma.ModelSchema):
id = fields.Integer()
class Meta:
model = Child
class PagedListSchema(Schema):
# ...snip...
pages = fields.Integer(dump_to='numPages', dump_only=True)
per_page = fields.Integer(dump_to='perPage', dump_only=True)
total = fields.Integer(dump_to='totalItems', dump_only=True)
class ParentPagedListSchema(PagedListSchema):
items = fields.Nested(ParentSchema, many=True, dump_only=True)
parent_paged_list_schema = ParentPagedListSchema()