python - Temporarily disable increment in SQLAlchemy -


i running flask application sqlalchemy (1.1.0b3) , postgres.

with flask provide api on client able instances of type database , post them again on clean version of flask application, way of local backup. when client posts them again, should again have same id had when downloaded them.

i don't want disable "increment" option primary keys normal operation if client provides id post , wishes give new resource said id set accordingly without breaking sqlalchemy. how can access/reset current maximum value of ids?

@app.route('/objects', methods = ['post']) def post_object():      if 'id' in request.json , myobject.query.get(request.json['id']) none: #1         object = myobject()         object.id = request.json['id']     else: #2         object = myobject()      object.fillfromjson(request.json)     db.session.add(object)     db.session.commit()     return jsonify(object.todict()),201 

when adding bunch of object id #1 , trying add on without id or used id #2, get.

duplicate key value violates unique constraint "object_pkey" detail:  key (id)=(2) exists. 

usually, id generated incrementally when id used, there no check that. how can between auto-increment , insert?

after adding object fixed id, have make sure normal incremental behavior doesn't cause collisions future insertions.

a possible solution can think of set next insertion id maximum id (+1) found in table. can following additions code:

@app.route('/objects', methods = ['post']) def post_object():     fixed_id = false     if 'id' in request.json , myobject.query.get(request.json['id']) none: #1         object = myobject()         object.id = request.json['id']         fixed_id = true     else: #2         object = myobject()      object.fillfromjson(request.json)     db.session.add(object)     db.session.commit()      if fixed_id:         table_name = myobject.__table__.name         db.engine.execute("select pg_catalog.setval(pg_get_serial_sequence('%s', 'id'), max(id)) %s;" % (table_name, table_name))      return jsonify(object.todict()),201 

the next object (without fixed id) inserted table continue id increment biggest id found in table.


Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -