WIth SQLModel in Python, I want to create one item of user and one of group associated to it.
class 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")
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
sqlalchemy.exc.IntegrityError: (sqlalchemy.dialects.postgresql.asyncpg.IntegrityError) <class 'asyncpg.exceptions.ForeignKeyViolationError'>: update or delete on table "user" violates foreign key constraint "group_user_id_fkey" on table "group"
DETAIL: Key (id)=(abcd) is still referenced from table "group".
[SQL: DELETE FROM "user" WHERE "user".id = %s]
[parameters: ('abcd',)]
Do you know how to fix that issue?