我正在尝试使用 SQLModel 作为 ORM。我的一些模型具有自定义验证、计算字段,或者只是我希望在创建或更改它们时发生的事情。我最终经常使用以下样板:
class MyModel(SqlModel):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.custom_method()
def update(self, **kwargs):
super().update(**kwargs)
self.custom_method()
def custom_method(self):
"""Do this when a model is created or updated
"""
pass
有什么好方法可以让这个语法变得更甜一点吗?理想情况下,我想要一个围绕函数的装饰器,它将函数调用注入到
__init__
和 update
:
class MyModel(SqlModel):
@run_on_change
def custom_method(self):
"""Do this when a model is created or updated
"""
pass
但是我不知道这是如何工作的,因为装饰器会在调用函数时拦截并修改其行为,而我想修改调用函数的环境。
或者,任何人都可以提出令人信服的论据来使用
@listens_for
装饰器而不是上述与模型本身相关的样板方法吗?
定义一个抽象基类作为
SQLModel
和具体子类之间的桥梁。
from abc import ABC, abstractmethod
class MyBaseModel(SQLModel):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.custom_method()
def update(self, **kwargs):
super().update(**kwargs)
self.custom_method()
@abstractmethod
def custom_method(self):
pass
class MyModel(MyBaseModel):
def custom_method(self):
"""Do stuff here"""