How to refactor columns that needs sa_solumn attribute across multiple SQLModel tables? #954
-
First Check
Commit to Help
Example Codefrom datetime import datetime, timezone
from typing import Optional
from sqlmodel import SQLModel, Field, create_engine, Session
from sqlalchemy import Column, DateTime
def get_utc_now()->datetime:
return datetime.now(timezone.utc)
class BaseModel(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))
class User(BaseModel,table=True):
user_details:str
class Product(BaseModel,table=True):
product_details:str
engine=create_engine("sqlite:///testdb.db")
SQLModel.metadata.create_all(engine)
def create_user():
with Session(engine) as session:
user = User(id=1)
session.add(user)
session.commit()
session.refresh(user)
print(user)
def create_product():
with Session(engine) as session:
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 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Found the answer. Had to use
|
Beta Was this translation helpful? Give feedback.
Found the answer. Had to use
sa_type
. Here's the fixed code: