8

我正在尝试使用 Flask 中的 Marshmallow 从一对多关系模型中序列化数据。我阅读了 Marshmallow 和 SQLAlchemy 文档,但无法正常工作。任何人都可以帮助我。

楷模:

class Category(db.Model):
    __tablename__ = 'category_mn'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(45))
    status = db.Column(db.Integer, server_default=db.FetchedValue())
    items = db.relationship('Items', backref='category', lazy='dynamic')
    timestamp = db.Column(db.DateTime, server_default=db.FetchedValue())


class Items(db.Model):
    __tablename__ = 'items_mn'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(100))
    category_id = db.Column(db.Integer, db.ForeignKey('category_mn.id'))
    timestamp = db.Column(db.DateTime, server_default=db.FetchedValue())

架构:

class CatSchema(ma.ModelSchema):
    class Meta:
        model = Category
        fields = ('id', 'name', 'status')


class ItemSchema(ma.ModelSchema):

    class Meta:
        model = Items
        fields = ('id', 'name')
    category = ma.Nested(CatSchema, many=True)

我正在寻找这样的输出:

[{'id':1, 'name':'Test', 'category':{'id':1, 'name':'Test Cat'}}]
4

1 回答 1

11

您正在引用架构中不存在的模型。

除此之外,categoryinItems是不可迭代的(它是“一对多”关系的“一”侧),因此many=True参数会引发错误。

并且category应该出现在类的fields属性中,所以它实际上出现在序列化中。MetaItemSchema

它应该是这样的:

class CatSchema(ma.ModelSchema):
  class Meta:
    model = Category
    fields = ('id', 'name', 'status')


class ItemSchema(ma.ModelSchema):

  class Meta:
    model = Items
    fields = ('id', 'name', 'category')
  category = ma.Nested(CatSchema)

当然,您可以根本不将fields属性包含在元类中,因为model它已经负责映射模型。

于 2017-06-13T02:51:56.290 回答