使用marshmallow序列化两个嵌套模式

Soh*_*oqi 7 python flask-sqlalchemy marshmallow

我对python很新.我有两个SQLAlchemy模型如下:

class listing(db.Model):
 id = db.Integer(primary_key=True)
 title = db.String()
 location_id = db.Column(db.Integer, db.ForeignKey('location.id'))
 location = db.relationship('Location', lazy='joined')

class location(db.Model):
 id = db.Integer(primary_key=True)
 title = db.String()
Run Code Online (Sandbox Code Playgroud)

我有两个Marshmallow架构类:

class ListingSchema(Schema):
 id = fields.Int()
 title = fields.Str()
 location_id = fields.Int()

class LocationSchema(Schema):
 id = fields.Int()
 title = fields.Str()
Run Code Online (Sandbox Code Playgroud)

我创建了一个嵌套的架构类,如:

class NestedSchema(Schema):
 listing = fields.Nested(ListingSchema)
 location fields.Nested(LocationSchema)
Run Code Online (Sandbox Code Playgroud)

我正在做连接查询,如:

listing,location = db.session.query(Listing,Location)\
                            .join(Location, and_(Listing.location_id == Location.id))\
                            .filter(Listing.id == listing_id).first()
Run Code Online (Sandbox Code Playgroud)

数据在我检查过的对象中加载.如何解析这个架构?我试过了

result,errors = nested_listing_Schema(listing,location)
Run Code Online (Sandbox Code Playgroud)

这给出了错误:"列表对象不可迭代."

Jai*_*rut 9

右边是使用你创建NestedSchema而不是nested_schema的类,执行以下操作:

result,errors = NestedSchema().dump({'listing':listing,'location':location})
Run Code Online (Sandbox Code Playgroud)

结果将是:

dict: {
       u'listing': {u'id': 8, u'title': u'foo'},
       u'location': {u'id': 30, u'title': u'bar'}
      }
Run Code Online (Sandbox Code Playgroud)

但是我不明白为什么你想制作一个"NestedSchema",我想你可以用另一种方式做到.

首先,忘记"NestedSchema"类.

之后,更改您的"ListingSchema",如下所示:

class ListingSchema(Schema):
    id = fields.Int()
    title = fields.Str()
    location_id = fields.Int()
    location = fields.Nested("LocationSchema") #The diff is here
Run Code Online (Sandbox Code Playgroud)

现在你可以这样做:

listing = db.session.query(Listing).get(listing_id) # Suppose listing_id = 8
result,errors = ListingSchema().dump(listing)
print result
Run Code Online (Sandbox Code Playgroud)

结果将是:

dict: {
        u'id': 8, u'title': u'foo', u'location_id': 30, u'location': {u'id': 30, u'title': u'bar'}
      }
Run Code Online (Sandbox Code Playgroud)

请注意,现在,"location"是"listing"的属性.

你仍然可以进行双向嵌套,只需在Listing(模型)中添加一个backref,并将ListingSchema添加为嵌套在LocationSchema中

class Listing(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(45), nullable=False)
    location_id = db.Column(db.Integer, db.ForeignKey('location.id'))
    location = db.relationship('Location', lazy='joined', backref="listings") #the diff is here

class LocationSchema(Schema):
    id = fields.Int()
    title = fields.Str()
    listings = fields.Nested("ListingSchema", many=True, exclude=("location",)) #The property name is the same as in bakcref
Run Code Online (Sandbox Code Playgroud)

many=True是因为我们有一对多的关系.这exclude=("location")是为了避免递归异常.

现在我们也可以按位置搜索.

location = db.session.query(Location).get(location_id) # Suppose location_id = 30
result,errors = LocationSchema().dump(location)
print result

dict: {u'id': 30, u'title': u'bar', 
       u'listings': [
             {u'location_id': 30, u'id': 8, u'title': u'foo'},
             {u'location_id': 30, u'id': 9, u'title': u'foo bar baz'},
             ...
             ]
       }
Run Code Online (Sandbox Code Playgroud)

你可以在这里看到有关它的文档