问题
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