ForeignKeyViolationError in Relationship deletion #1467
-
First Check
Commit to Help
Example Codeclass User(SQLModel, table=True):
id: str = Field(primary_key=True, nullable=False)
group: Optional["Group"] = Relationship(
sa_relationship_kwargs={"uselist": False, "cascade": "save-update,merge,expunge,delete,delete-orphan"},
back_populates="user")
class Group(SQLModel, table=True):
group_id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True, index=True, nullable=False)
user_id: Optional[str] = Field(default=None, foreign_key="user.id", nullable=True)
user: Optional["User"] = Relationship(back_populates="group") DescriptionI want to create one item of user and one of group associated to it. That works nicely when creating a user and an associated group, but when I want to delete the user, the associated group should be deleted as well. However it gives me the following error message
Do you know how to fix that issue? Operating SystemmacOS Operating System DetailsNo response SQLModel Version0.0.8 Python Version3.9 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments
-
Yep it's because you have You have defined cascades however, maybe it needs to be in the relationship in Group with back_populates though? |
Beta Was this translation helpful? Give feedback.
-
@antont Many thanks for getting back to me. Since, I am not very experienced here, could you adapt the code from above, such that I could try it out? 😀 |
Beta Was this translation helpful? Give feedback.
-
@antont Here is what I tried now
and tried to post a user, I got
Also, when using the same situation without
I still get
Does that help here? |
Beta Was this translation helpful? Give feedback.
-
Did you really though? Could you show the SQLAlchemy equivalent code that you tried to make sure that this behavior is any different with SQLAlchemy? |
Beta Was this translation helpful? Give feedback.
-
You can read more about cascade delete relationships in docs: https://sqlmodel.tiangolo.com/tutorial/relationship-attributes/cascade-delete-relationships/ |
Beta Was this translation helpful? Give feedback.
Yep it's because you have
foreign_key="user.id"
in Group, so you can't delete a user when a group refers to it.You have defined cascades however, maybe it needs to be in the relationship in Group with back_populates though?