0

I trying to put a nested model and it's works, but i can see a new row in my database created in the same time.

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)

(i think it's a problem with my nested schema)

schemas:

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')

In addition to the update, a line is created when I send this body:

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

It's my first post, teel me if you need more information and I'm sorry for my very aproximative english

  • I wouldn't expect your example code to add a new row as you are querying and modifying an existing row in the database, not creating a new instance of `Program`. `db.session.add(program)` is a no-op if `program` is an instance returned from a query as it is already being tracked by the session. – SuperShoot Dec 01 '18 at 23:05
  • I edited my post with the body I use for put my program. Is it help for understand why have this line created in addition? Thanks for your help – Berenger Salmon Dec 05 '18 at 11:54
  • set `dump_only` to your fields and you won't get data to insert to your database. – Shihe Zhang Jan 23 '19 at 08:05

0 Answers0