2014-07-25 35 views
2

我有一個SLQALchemy對象,正在序列化爲marshmallow序列化具有多個子項的子項的SQLAlchemy對象

該對象有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。當我在那裏登錄一些東西時,看起來棉花糖試圖訪問<Comment>列表的text屬性。它應該分別訪問每個<Comment>,然後訪問text屬性。

我是否在我的序列化程序中缺少某些內容?我知道發送ParentSerializer中的many=True參數告訴棉花糖它應該遍歷<Parent>列表。有沒有辦法告訴棉花糖,它也應該期待很多<Comment><Like>

回答

8

有沒有辦法告訴棉花糖,它也應該期待很多<Comment><Like>

是的。您也可以將many=True傳遞給Nested字段。

class ParentSerializer(Serializer): 
    comments = fields.Nested(CommentSerializer, many=True) 
    likes = fields.Nested(LikeSerializer, many=True) 
相關問題