我正在使用flask-marshmallow以及marshmallow-sqlalchemy
我想要拥有自己的 HATEOAS 实现:对于 n 对多关系,以及链接,我想要获得对象的计数
为此,我有一个具有多对多关系的常规 sqlalchemy 模型:
class ParentChild(Model):
__tablename__ = 'parrent_child'
parent_id =Column(Integer, ForeignKey('parent.id'), primary_key=True)
child_id = Column(Integer, ForeignKey('child.id'), primary_key=True)
class Parent(Model):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
name = Column(String())
children = relationship('Child', secondary='parent_child', back_populates='parents')
class Child(Model):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
name = Column(String())
parents = relationship('Parent', secondary='parent_child', back_populates='children')
使用以下棉花糖模式,我设法获取我想要的数据:
class ParentSchema(Schema):
class Meta:
model = Parent
children = URLFor('api.parents_children_by_parent_id', parent_id='<id>')
children_count = base_fields.Function(lambda obj: len(obj.children))
返回:
{
"id" : 42,
"name" : "Bob",
"children" : "/api/parents/42/children",
"children_count" : 3
}
但是当我想像这样封装字段时遇到问题:
{
"id": 42
"name": "bob",
"children": {
"link": "/api/parents/42/children",
"count": 3
}
}
我尝试使用 base_fields.Dict
:
children = base_fields.Dict(
link = URLFor('api.parents_children_by_parent_id', parent_id='<id>'),
count = base_fields.Function(lambda obj: len(obj.children))
)
但是我明白了
TypeError: Object of type 'Child' is not JSON serializable
我尝试了各种其他解决方案,但没有成功:
flask 棉花糖Hyperlinks
只接受
超链接的字典,而不是函数的字典。
我认为解决方案是使用 base_fields.Nested
但它破坏了 URLFor
的行为无法捕获 '<id>'
。
我在文档中找不到此问题的解决方案。
在某些时候,很难跳出框框思考。我错过了什么吗?任何帮助将不胜感激。
最佳答案
所以我找到了一个解决方法,我将发布它,但我认为它可以改进。
覆盖children
字段与我想要的对象,我使用 base_fields.Method
:
class ParentSchema(Schema):
class Meta:
model = Parent
children = base_fields.Method('build_children_obj')
def build_children_obj(self, obj):
return {
"count": len(obj.children),
"link": URLFor('api.parents_children_by_parent_id', parent_id=obj.id)
}
那时,我得到了 TypeError: Object of type 'URLFor' is not JSON serializable
检查 _serialize
的来源后方法URLFor
我在我的(自定义)JSONEncoder 中添加了一个检查:
if isinstance(o, URLFor):
return str(o._serialize(None, None, o))
我终于得到了我想要的有效负载,但我发现它不是很干净。有什么想法吗?
编辑:经过测试,我发现 len(obj.children)
通过加载整个子列表来获取计数在资源上非常昂贵。相反,我这样做db.session.query(func.count(Children.id)).filter(Children.parents.any(id=obj.id)).scalar()
哪个更优化。
关于python - Flask-marshmallow base_fields.base_fields.Nested 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51257431/