"UniqueViolation, duplicate key value violates unique constraint" on update #581
Replies: 4 comments 1 reply
-
I'm having the exact same problem right now. For me, it's only happening when I change things in the model's relationship. This is definitely buggy behavior, as this should not cause the model to be seen as new. stmt = select(MyModel).where(MyModel.indexed_column == query_value)
existing = self.db.execute(stmt).scalar_one_or_none()
existing.relationship_to_things = [thing1, thing2, thing3]
self.db.commit() gives unique key constraint violation on the primary key of I've tried calling |
Beta Was this translation helpful? Give feedback.
-
See above, at least for me, this happens when I try to replace or add to a relationship for my existing row. To get around this, I did the following: for hero in existing_team.heroes:
session.delete(hero)
session.flush()
for hero in new_heroes:
db_hero = Hero(
name = hero.name,
# etc.
)
session.add(db_hero)
session.commit() |
Beta Was this translation helpful? Give feedback.
-
I guest you should not use |
Beta Was this translation helpful? Give feedback.
-
I stumbled upon this thread and I have solved a similar issue with merge(). I'm not sure if this is really the same problem but I guess it doesn't hurt to mention it here. Note that merge() comes with its own drawbacks as written below under "Merge Tips". basically replace add() with merge(). |
Beta Was this translation helpful? Give feedback.
-
First Check
Commit to Help
Example Code
Description
I have an edpoint for updating records in the database, but it doesn't seem to work as intended and I get the following error when I call the endpoint to update a record:
In another controller I'm using
session.get(Parent, id)
and the updating process works fine, but for this specific controller I'm usingsession.execute(text("query"))
because of this issue and update doesn't work (violates unique constraint
). How can I fix this issue?Operating System
macOS
Operating System Details
No response
SQLModel Version
0.0.8
Python Version
3.9.13
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions