Skip to content

ForeignKeyViolationError in Relationship deletion #457

@junoriosity

Description

@junoriosity

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the SQLModel documentation, with the integrated search.
  • I already searched in Google "How to X in SQLModel" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to SQLModel but to Pydantic.
  • I already checked if it is not related to SQLModel but to SQLAlchemy.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

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")

Description

I 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

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?

Operating System

macOS

Operating System Details

No response

SQLModel Version

0.0.8

Python Version

3.9

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions