Skip to content
Advertisement

How to fix IntegrityError: (psycopg2.errors.ForeignKeyViolation) update or delete on table “users” violates foreign key constraint

I have two tables created with Flask-SQLAlchemy below – they have a one to one relationship.

JavaScript

I would like to update the user table in a case when the user would like to have a new username:

JavaScript

The db.session.commit throws the following error:

JavaScript

The error says the logo table still has the old username but I have updated it and I don’t know why that shows up again, I have spent the last 2 hours debugging and trying different stuff but nothing works.

Advertisement

Answer

You could temporarily make the foreign key constraint deferrable and make the update in psql. Say we have these tables:

JavaScript

then the statements would be

JavaScript

Deferring the constraint means updates are evaluated at the end of the transaction rather than immediately, so the the point of view of the database the columns are not out of sync.

The long term solution is to use users.id as the foreign key, as it is less likely to change.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement