我试图阅读有关序列化的现有问题flask-Marshmallow
,但我似乎无法得到我想要的东西,我想知道缺少什么:
我想得到这样的回应:
{
"data": [ {"name": "Netherlands tour",
"description": "This is a fascinating tour to take ...",
"price": 30.0,
"available_dates":[
{
"date": "2018-05-05"
},
{
"date": "2018-07-07"
}
],
"destinations":[
{
"location":"A",
"tour_type":"Adventure",
"danger_type":"Low"
},
{
"location":"B",
"tour_type":"Leisure",
"danger_type":"Medium"
}
],
"capacity": 30},
...
]
}
但我没有得到它,我只是得到这个:
{
"data": [
{
"capacity": 30,
"description": "This is a fascinating tour to take",
"name": "Europe tour",
"price": 30.0
},
{
"capacity": 30,
"description": "This is a fascinating tour to take",
"name": "Europe tour",
"price": 30.0
},
{
"capacity": 30,
"description": "This is a fascinating tour to take",
"name": "Europe tour",
"price": 30.0
},
{
"capacity": 30,
"description": "This is a fascinating tour to take",
"name": "Europe tour",
"price": 30.0
}
]
下面是我的模型:
class TourPackages(db.Model):
__tablename__ = 'tourpackage'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
description = db.Column(db.TEXT)
price = db.Column(db.Float)
destinations = db.relationship('Destinations', backref='destination_id', lazy='dynamic')
available_dates = db.relationship('AvailableDates', backref='available_date_id', lazy='dynamic')
capacity = db.Column(db.Integer)
created_on = db.Column(db.DateTime(), default=datetime.utcnow)
class Destinations(db.Model):
__tablename__ = 'destinations'
id = db.Column(db.Integer, primary_key=True)
tour_Packages = db.Column(db.Integer, db.ForeignKey('tourpackage.id'))
location = db.Column(db.String(50))
tour_type = db.Column(db.String(50))
danger_type = db.Column(db.String(50))
class AvailableDates(db.Model):
__tablename__ = 'availabledates'
id = db.Column(db.Integer, primary_key=True)
date_available = db.Column(db.String(50))
tour_date = db.Column(db.Integer, db.ForeignKey('tourpackage.id'))
然后,这是我的棉花糖模式:
class DestinationSchema(ma.Schema):
class Meta:
model = Destinations
sqla_session = Session
fields = ('id', 'location', 'danger_type')
class AvailableDatesSchema(ma.Schema):
class Meta:
model = AvailableDates
sqla_session = Session
fields = ('id', 'date_')
class TourPackagesSchema(ma.Schema):
class Meta:
model = TourPackages
fields = ('id', 'name', 'description', 'price', 'capacity')
destiantion = fields.Nested(DestinationSchema, many=True)
available = fields.Nested(AvailableDatesSchema, many=True)
然后,在我的GET
请求方法中,这是我的代码:
def get_all_tours(self):
tours = db.session.query(TourPackages.name, TourPackages.description, TourPackages.price,
TourPackages.capacity,
Destinations.location,
Destinations.tour_type,
Destinations.danger_type, AvailableDates.date_available).join(
Destinations).join(AvailableDates).all()
tour_schema = TourPackagesSchema(many=True)
dump_data = tour_schema.dump(tours)
output = jsonify({'data' : dump_data})
return output
我缺少什么来序列化嵌套的 json 响应?