-
First Check
Commit to Help
Example Codefrom typing import Optional
from sqlmodel import Field, SQLModel
class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
secret_name: str
age: Optional[int] = None
def save(self,*args, **kwargs)):
.....
return super(Hero,self).save(*args, **kwargs) DescriptionIt's gonna override or deal like callback the save , update or delete method Operating SystemmacOS Operating System DetailsNo response SQLModel Versionfrom model.hero import Hero Python Version3.13.0 Additional ContextHi, I want to know is that possible to add a callback before or after save, update,delete in my model? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Hey, what do you mean by a 'callback' ? You can pass a function as an argument and call it if that's what you want, if you can be a bit more precise on what you are trying to achieve 😄 And just a small consideration, but I would suggest you to have your models only for modelling and than have your operations elsewhere. You can have a look at my example project if interested https://github.com/joachimhuet/sqlmodel-project-example |
Beta Was this translation helpful? Give feedback.
-
Hey! I think you're looking for SQLAlchemy's ORM Events, namely Mapper Events. You'll likely find a lot more information if you search for information related to SQLAlchemy rather than SQLModel (which uses SQLAlchemy internally), but here's a small example showcasing how these events work: from sqlmodel import Field, SQLModel, create_engine, Session
from sqlalchemy import event
class Hero(SQLModel, table=True):
name: str = Field(primary_key=True)
secret_name: str = Field()
# Option 1: Setting the event listener on the class
def insert_is_done(mapper, connection, target):
print("I just created a new Hero!")
event.listen(Hero, "after_insert", insert_is_done)
# Option 2: Setting the event listener on the method
@event.listens_for(Hero, "before_insert")
def before_insert(mapper, connection, target):
print("I'm about to create a new Hero!")
# Create the database
engine = create_engine("sqlite:///example.db")
SQLModel.metadata.create_all(engine)
# Create a Hero
hero_1 = Hero(name="Spider-Man", secret_name="Peter Parker")
with Session(engine) as session:
session.add(hero_1)
session.commit() Note that these operations are ran during the |
Beta Was this translation helpful? Give feedback.
Hey! I think you're looking for SQLAlchemy's ORM Events, namely Mapper Events. You'll likely find a lot more information if you search for information related to SQLAlchemy rather than SQLModel (which uses SQLAlchemy internally), but here's a small example showcasing how these events work: