Uh oh!
There was an error while loading. Please reload this page.
How to refactor columns that needs sa_solumn attribute across multiple SQLModel tables? #954
First Check
Commit to Help
Example Codefromdatetimeimportdatetime, timezonefromtypingimportOptionalfromsqlmodelimportSQLModel, Field, create_engine, SessionfromsqlalchemyimportColumn, DateTimedefget_utc_now()->datetime:
returndatetime.now(timezone.utc)
classBaseModel(SQLModel):
id:int=Field(primary_key=True)
created_at:Optional[datetime]=Field(sa_column=Column(DateTime(timezone=True),default=get_utc_now))
updated_at:Optional[datetime]=Field(sa_column=Column(DateTime(timezone=True),default=get_utc_now,onupdate=get_utc_now))
classUser(BaseModel,table=True):
user_details:strclassProduct(BaseModel,table=True):
product_details:strengine=create_engine("sqlite:///testdb.db")
SQLModel.metadata.create_all(engine)
defcreate_user():
withSession(engine) assession:
user=User(id=1)
session.add(user)
session.commit()
session.refresh(user)
print(user)
defcreate_product():
withSession(engine) assession:
product=Product(id=1)
session.add(product)
session.commit()
session.refresh(product)
print(product)
create_user()
create_product()DescriptionMy tables have a few columns whose definition are similar. I would love to write this code once and use it across all tables. Unfortunately, this does not work when I use the sa_column attribute. For example, created_at is a datetime with timezone aware type. I couldn't find a way to do this in SQLModel. Hence I used the sa_column attribute. Exception: Exception has occurred: ArgumentError Operating SystemmacOS Operating System DetailsTried on both MacOS 14.4 and 12.7 SQLModel Version0.0.18 Python Version3.11.8 Additional ContextNo response |
Replies: 1 comment 1 reply
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Found the answer. Had to use |
Found the answer. Had to use
sa_type. Here's the fixed code: