sqlmodel
sqlmodel copied to clipboard
✨ Allow specifying the `foreign_key` using an instance of `ForeignKey`
~~…to let the user define additional sqlalchemy.orm.ForeignKey attributes, such as ondelete and onupdate, for foreign keys defined in a base model.~~
UPD YuriiMotov:
Currently we can specify foreign_key as an instance of sqlalchemy.ForeignKey passing it via sa_column_args:
class Item(SQLModel, table=True):
owner_id: Optional[int] = Field(
default=None, sa_column_args=(ForeignKey("user.id", ondelete="SET NULL"),)
)
But in current implementation it doesn't work if we use inheritance:
class Base(SQLModel):
owner_id: Optional[int] = Field(
default=None, sa_column_args=(ForeignKey("user.id", ondelete="SET NULL"),)
)
class Asset(Base, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
class Document(Base, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
The code above will lead to "This ForeignKey already has a parent" error.
This PR fixes that error and allows passing an instance of ForeignKey as a value of foreign_key parameter of Field:
class Item(SQLModel, table=True):
owner_id: Optional[int] = Field(
default=None,
foreign_key=ForeignKey("user.id", ondelete="SET NULL"),
)