Deleting a model that doesn't keep back references to its relationships -- with PR #611
Replies: 2 comments
-
This is the sqlalchemy version of this question: |
Beta Was this translation helpful? Give feedback.
-
The code example from initial post works fine (after fixing couple of obvious things): See full code in the details: from sqlmodel import Field, Relationship, SQLModel, create_engine, Session
class Repository(SQLModel, table=True):
id: int = Field(primary_key=True)
...
class User(SQLModel, table=True):
id: int = Field(primary_key=True)
...
name: str
repository_id: int | None = Field(foreign_key='repository.id')
repository: Repository | None = Relationship()
sqlite_url = "sqlite:///"
engine = create_engine(sqlite_url, echo=True)
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
# -- first create a user without a repository
user = User(name='some user')
session.add(user)
session.flush()
# -- create and add the repository
rep = Repository()
user.repository = rep
session.add(rep)
session.flush()
session.commit()
# -- now delete the user's repository
session.delete(rep)
session.commit()
session.refresh(user)
print(user.repository) # Should be None, as the repository was deleted This section of docs explains how to use |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
First Check
Commit to Help
Example Code
Description
The above code would raise the error:
One workaround would be to add the back reference from
Repository
toUser
. In this case it makes sense, although for my use case it would clutter my models and make them less semantically coherent.Operating System
macOS
Operating System Details
No response
SQLModel Version
0.0.8
Python Version
3.10.0
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions