Python 用棉花糖序列化两个嵌套模式

Python 用棉花糖序列化两个嵌套模式,python,flask-sqlalchemy,marshmallow,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 loca

我对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()
我为他们提供了两个棉花糖模式类:

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

class LocationSchema(Schema):
 id = fields.Int()
 title = fields.Str()
我创建了一个嵌套的模式类,如:

class NestedSchema(Schema):
 listing = fields.Nested(ListingSchema)
 location fields.Nested(LocationSchema)
我正在执行连接查询,如下所示:

listing,location = db.session.query(Listing,Location)\
                            .join(Location, and_(Listing.location_id == Location.id))\
                            .filter(Listing.id == listing_id).first()
数据在我检查过的对象中加载。如何解析这个模式? 我试过了

result,errors = nested_listing_Schema(listing,location)

这会产生错误:“列出对象是不可迭代的。”

正确的做法是使用您创建的NestedSchema和not nested_schema类,请执行以下操作:

result,errors = NestedSchema().dump({'listing':listing,'location':location})
结果将是:

dict: {
       u'listing': {u'id': 8, u'title': u'foo'},
       u'location': {u'id': 30, u'title': u'bar'}
      }
但我不明白你为什么要做一个“嵌套模式”,我想你可以用另一种方式来做

首先,忘记类“NestedSchema”

之后,更改“ListingSchema”,如下所示:

class ListingSchema(Schema):
    id = fields.Int()
    title = fields.Str()
    location_id = fields.Int()
    location = fields.Nested("LocationSchema") #The diff is here
现在你可以做:

listing = db.session.query(Listing).get(listing_id) # Suppose listing_id = 8
result,errors = ListingSchema().dump(listing)
print result
结果将是:

dict: {
        u'id': 8, u'title': u'foo', u'location_id': 30, u'location': {u'id': 30, u'title': u'bar'}
      }
请注意,现在,“location”是“listing”的属性

您仍然可以创建一个,只需在清单(模型)中添加一个backref,并在LocationSchema中添加嵌套的ListingSchema

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
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'},
             ...
             ]
       }

您可以看到关于它的文档

显示嵌套的清单模式的源代码
类嵌套模式