How to nest some parent object fields when serializing objects using marshmallow

前提是你 提交于 2019-12-23 22:16:00

问题


I'm using marshmallow to serialize a sqlalchemy object that has a flat structure like:

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)

When serializing, I would like marshmallow to group the related address fields like this:

{'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'}}

Is there a way to get marshmallow to do this without using @post_dump? I know I can nest other schemas with Nested(), but in this case I just would like to nest certain columns from the parent schema itself.


回答1:


Maybe... In your Schema class add a field.Method:

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}}

Take a look at Marshmallow Documentation



来源:https://stackoverflow.com/questions/35881744/how-to-nest-some-parent-object-fields-when-serializing-objects-using-marshmallow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!