SQLAlchemy: duplicate key violation because of old record that I delete in same session

47 Views Asked by At

I currently have a User table (with some child tables). Upon doing a POST request, I'm trying to see if a user already exists, if so delete that user, and create a new User object/table (with the updated information).

This process looks like this:

with Session(engine) as session:
    stmt = delete(User).where(User.id == user_id)
    session.execute(stmt)
    session.commit()

    ...simplified but essentially...
    deserialized_user = User(user_id, ...)

    session.add(deserialized_user)
    session.commit()

Here, the user_id is the primary key and should obviously be unique.

However, I assumed that if I delete my User with <user_id> first, I should then be able to add it as it is no longer there. However this does not seem to be the case, as I get a duplicate key violation on the primary key of my User table.

How can I solve this? Thanks a lot in advance.

0

There are 0 best solutions below