How to create a basemodel with relationship? #858
-
First Check
Commit to Help
Example Codefrom __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING, Optional
from sqlalchemy import func
if TYPE_CHECKING:
from .user import User # noqa: F401
from sqlmodel import Field, Relationship, SQLModel
class EditableBase:
create_time: datetime = Field(sa_column_kwargs=dict(server_default=func.now()))
update_time: datetime = Field(sa_column_kwargs=dict(server_default=func.now(), onupdate=func.now()))
create_id: int | None = Field(foreign_key="user.id")
creator: Optional["User"] = Relationship(sa_relationship_kwargs=dict(foreign_keys=[create_id]))
update_id: int | None = Field(foreign_key="user.id")
updater: Optional["User"] = Relationship(sa_relationship_kwargs=dict(foreign_keys=[update_id])) DescriptionI want to create a base class for every models in my project, all of them need creator and updater. But if I use it as parent class of my model, this error appears:
Operating SystemLinux Operating System DetailsNo response SQLModel Version0.0.16 Python VersionPython 3.10.12 Additional Contextthis question is different with #488 , My basemodel is not a real table but just a "template" |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
You mean something like how to inherit ?
|
Beta Was this translation helpful? Give feedback.
-
I think you are just missing the parent class specification: But from experience it's not a good idea to define relationships in base class, it caused me so many problems. Now I just put the type and default value for relationships in Base and specify the relationship in Table class. That is where it will actually be used anyway. Example:
|
Beta Was this translation helpful? Give feedback.
I think you are just missing the parent class specification:
class EditableBase(SQLModel)
But from experience it's not a good idea to define relationships in base class, it caused me so many problems.
Now I just put the type and default value for relationships in Base and specify the relationship in Table class. That is where it will actually be used anyway.
Example: