我试图放入一个嵌套模型,并且可以使用,但是我可以看到同时创建的数据库中的新行。
api / program.py:
@app.route("/programs/<id>", methods=["PUT"])
def update_program(id):
program = Program.query.filter_by(id=id).first()
res = program_nested_schema.load(request.json)
program.name = res.data.name
program.steps = res.data.steps
program.updated_at = datetime.utcnow()
db.session.add(program)
db.session.commit()
return program_nested_schema.jsonify(program)
(我认为这是我的嵌套模式存在的问题)
方案:
class ProgramNested(ma.ModelSchema):
class Meta:
model = Program
fields = ('name', 'visibility', 'steps')
steps = fields.Nested(ProgramStepsSchema, many=True)
program_nested_schema = ProgramNested()
class ProgramStepsSchema(ma.ModelSchema):
class Meta:
model = Step
exercise = fields.Nested(GetExerciseSchema, many=False, only=('id',))
class GetExerciseSchema(ma.ModelSchema):
class Meta:
model = Exercise
fields = ('id', 'name', 'image', 'visibility')
除了更新之外,我发送此正文时还会创建一行:
{
"id": 2,
"name": "Jambes",
"steps": [
{
"exercise": {
"id": 6,
"image": "pompe.jpg",
"name": "Pompes"
},
"id": 6,
"position": 1,
"repetitions": 200,
"rest": 30,
"rest_end": 60,
"series": 3,
"weight": 0
},
{
"exercise": {
"id": 7,
"image": "10763352.jpg",
"name": "Squats"
},
"id": 70,
"position": 2,
"repetitions": 11,
"rest": 45,
"rest_end": 90,
"series": 4,
"weight": 16
}
],
"visibility": "PRIVATE"
}
这是我的第一篇文章,如果您需要更多信息,请告诉我,我很抱歉我的英语水平