-
-
Notifications
You must be signed in to change notification settings - Fork 783
Add kwargs to ForeignKey definitions #610
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
|
I guess this would support this case as well? #436 I don't know if it's the way forward, or not, but am curious about opinions. |
|
I think so. |
|
Any hints how to properly set ondelete behavior with foreign keys? I'm trying to figure out how to SET NULL when foreign key is being deleted, but couldn't find a solution which wouldn't throw errors. Django ORM does a great job by exposing model methods, but here with SQLAlchemy, kwargs would also do. Just need a working solution. |
|
@tiangolo Any takes here? There is an issue I'm running into where defining a foreign_key as part of the "sa_column_args" in a BaseModel for a given object (let's say HeroBase) causes the relationships defined in a HeroRead that inherits from it to fail to find the FK. It works if I define it in the Though perhaps it would be even better to solve the issue of FKs defined at the |
|
In current version there is repository_id: int | None = Field(
foreign_key="repository.id", ondelete="SET NULL"
)This is documented here: https://sqlmodel.tiangolo.com/tutorial/relationship-attributes/cascade-delete-relationships/ And, if you need to pass other repository_id: int | None = Field(
sa_column_args=[ForeignKey("repository.id", ondelete="SET NULL")]
)IMO, this way is better since you will have all type hints (as opposed to Having this, I suggest we close this PR. |
|
This pull request has a merge conflict that needs to be resolved. |
|
Thanks @YuriiMotov for the clear clarification! 🙌 Agreed with all, yep, for now I'll pass on this one. Thanks! ☕ |
ForeignKeydefinitions in SqlAlchemy accept kwargs such asonupdateandondeletethat determine the behaviour of the foreign key at the DB level. This PR adds the option to provide kwargs to theForeignKeydefinition under the hood. In my case, I used it to control delete behaviour when deleting a model that did not maintain back references (relationships) with its child models. Example -- an application where users can have 0 or 1 "Repository":If we didn't set the
ondelete="SET NULL"option on theuser.repository_idforeign key we would get this error:A workaround for this would be to keep a
user: User = Relationship(back_populates='repository')attribute which I didn't want to do because in my case it would clutter my model. I'm wondering whether there are more concrete use cases for theforeign_key_kwargsoption.