I have some code, and every now and then (not always) when I try to insert a new record I run into an integrity error:
IntegrityError: (IntegrityError) duplicate key value violates unique constraint "question_pkey" DETAIL: Key (id)=(1) already exists.
I read somewhere on here that it's not a Postgres error, so it may have something to do with my code.
When I do a curl I'm inserting these things:
curl 127.0.0.1:5000/test/question -d '{"question_order": 6, "question_admin_type": 2}'
My code looks like:
def post(self, question_id=0):
post_args = request.get_json(force=True)
if question_id == 0: # assume new record
question_obj = Question(**post_args)
db.session.add(question_obj)
db.session.flush()
db.session.commit()
The error message seems to point towards the db.session.flush() but I don't know why. It seems like there's a problem with the line before it. It seems like my program tries to insert starting at the first-most id, and if that fails then it throws this error. On the next insert attempt (using cURL), it will try the next id, do the same thing if there is already an entry using that id and it'll continue to happen until it reaches an unused id. I'm also using the flask-sqlalchemy extension, if that's relevant.