Does sqlmodel support ORM events as sqlalchemy does? #648
-
First Check
Commit to Help
Example Codefrom typing import List, Optional
from sqlalchemy import Column, JSON, event
from sqlmodel import SQLModel, Field, Relationship
class Base(SQLModel):
id: int = Field(default=None, nullable=False, primary_key=True)
class Config:
arbitrary_types_allowed = True
class Task(Base, table=True):
title: str
type: str = Field(nullable=False)
# SQLAlchemy ORM Events listener
@event.listens_for(Task.__table__, 'after_commit') # ideally this should be common table to provide logging action
def receive_after_commit(session):
# write changes to AuditLog table DescriptionI am trying to create audit table for my application. I need to log all changes (at least CREATE, UPDATE actions) to AuditLog database table, to keep changes history of every record with user, action and fields information. Could not find any examples in SQLModel documentation, but SQLAlchemy provides ORM Events to implement this. Is it possible to do with SQLModel tables?
this code raises error: I need to get sqlalchemy class for sqlmodel Task class. Is it possible to do? If yes, how to get such class for common model to avoid code duplication? Operating SystemmacOS Operating System DetailsNo response SQLModel Version0.0.8 Python Version3.11.4 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
I'd guess it's possible, and that the answer is there, but I could not grasp the metamodel programming enough to get it. https://github.com/tiangolo/sqlmodel/blob/main/sqlmodel/main.py#L209 |
Beta Was this translation helpful? Give feedback.
-
I'm not sure if something changed or perhaps I'm just targeting a different event at the model level vs the table level, but this code is working for me to trigger events after_insert:
I previously tried to post code that I thought was working but in fact wasn't. I got tripped up on the jump from my async endpoints to synchronous listener function. |
Beta Was this translation helpful? Give feedback.
I'm not sure if something changed or perhaps I'm just targeting a different event at the model level vs the table level, but this code is working for me to trigger events after_insert:
I previously tried to post code that I thought was working but in fact wasn't. I got tripped up on the jump from my async endpoints to synchronous listener function.