使用marshmallow序列化对象时如何嵌套一些父对象字段

时间:2016-03-09 02:19:37

标签: python sqlalchemy marshmallow

我使用marshmallow来序列化具有扁平结构的sqlalchemy对象,如:

class Company(Base):
   __tablename__ = 'Company'
   id = sa.Column(sa.Integer, primary_key=True)
   MainStreetAddress = sa.Column(sa.String)
   MainCity = sa.Column(sa.String)
   MainState = sa.Column(sa.String)
   MainZip = sa.Column(sa.String)
   AltStreetAddress = sa.Column(sa.String)    
   AltCity = sa.Column(sa.String)
   AltState = sa.Column(sa.String)
   AltZip2 = sa.Column(sa.String)

序列化时,我希望marshmallow将相关的地址字段分组如下:

{'id':1,
 'main_address':{'street_address':'101 main    st','city':'springfield','state':'IL','zip':'11231'},
 'alt_address':{'street_address':'102 main st','city':'new bedford','state':'MA','zip':'07630'}}

有没有办法让marshmallow在不使用@post_dump的情况下执行此操作?我知道我可以使用Nested()嵌套其他模式,但在这种情况下,我只想嵌套父模式本身的某些列。

1 个答案:

答案 0 :(得分:0)

也许......在你的Schema类中添加一个字段。方法:

class Company(Base):
    __tablename__ = 'Company'
    id = sa.Column(sa.Integer, primary_key=True)
    MainStreetAddress = sa.Column(sa.String)
    MainCity = sa.Column(sa.String)
    MainState = sa.Column(sa.String)
    MainZip = sa.Column(sa.String)
    AltStreetAddress = sa.Column(sa.String)    
    AltCity = sa.Column(sa.String)
    AltState = sa.Column(sa.String)
    AltZip2 = sa.Column(sa.String)

class CompanySchema(Schema):
    id = fields.Integer()
    main_address = fields.Method('make_main_address')
    alt_address = fields.Method('make_alt_address')

    def make_main_address(self, obj)
        return {'main_address':{'street_address':obj.MainStreetAddress,'city':obj.MainCity ,'state':obj.MainState,'zip':obj.MainZip}}

    def make_alt_address(self, obj)
        return {'alt_address':{'street_address':obj.AltStreetAddress,'city':obj.AltCity ,'state':obj.AltState,'zip':obj.AltZip2}}

查看Marshmallow Documentation