我有一个用marshmallow序列化的 SLQALchemy 对象。
该对象有 N 个赞和 N 个评论。它看起来像这样:
class Parent():
__tablename__ = 'parent'
title = Column(db.String(100), unique=True, nullable=False)
description = Column(db.String(500))
created_at = Column(db.DateTime, nullable=False, default=dt.datetime.utcnow)
comments = relationship('Comment')
likes = relationship('Like')
序列化程序如下所示:
class CommentSerializer(Serializer):
class Meta:
fields = ('id', 'text', 'created_at', 'parent_id')
class LikeSerializer(Serializer):
class Meta:
fields = ('id', 'created_at', 'parent_id')
class ParentSerializer(Serializer):
comments = fields.Nested(CommentSerializer)
likes = fields.Nested(LikeSerializer)
class Meta:
fields = ('id', 'title', 'description', 'comments', 'likes')
我尝试像这样在视图中运行它:
allParents = Parent.query.all()
并将其转换为 JSON:
return jsonify({"parents": ParentSerializer(allParents, many=True).data})
当我尝试运行它时,我得到一个错误list indices must be integers, not str
。它来自marshmallow/serializer.py
. 当我在那里记录一些东西时,看起来棉花糖正在尝试访问text
. <Comment>
它应该单独访问每个<Comment>
然后访问该text
属性。
我的序列化程序中是否缺少某些内容?我知道many=True
在 ParentSerializer 中发送参数会告诉 marshmallow 它应该遍历<Parent>
. 有没有办法告诉棉花糖它也应该期待很多<Comment>
或<Like>
?