Peewee 如何为依赖项调用 post_delete 信号?
Peewee How do i call post_delete signal for dependencies?
我看到peewee有信号http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#signals
但它只适用于 delete_instance()
。
For what I hope are obvious reasons, Peewee signals do not work when
you use the Model.insert(), Model.update(), or Model.delete() methods.
These methods generate queries that execute beyond the scope of the
ORM, and the ORM does not know about which model instances might or
might not be affected when the query executes.
Signals work by hooking into the higher-level peewee APIs like
Model.save() and Model.delete_instance(), where the affected model
instance is known ahead of time.
那么,既然信号对依赖性使用 delete()
,我该如何在依赖性记录上使用信号?
def delete_instance(self, recursive=False, delete_nullable=False):
if recursive:
dependencies = self.dependencies(delete_nullable)
for query, fk in reversed(list(dependencies)):
model = fk.model
if fk.null and not delete_nullable:
model.update(**{fk.name: None}).where(query).execute()
else:
model.delete().where(query).execute()
return type(self).delete().where(self._pk_expr()).execute()
简短的回答是你不能,因为递归删除是使用以下形式的查询实现的:
DELETE FROM ... WHERE foreign_key_id = X
例如,假设您有一个用户并且他们创建了 1000 条推文。 tweet.user_id 指向 user.id。当您删除该用户时,peewee 发出 2 个查询:
DELETE FROM tweets WHERE user_id = 123
DELETE FROM users WHERE id = 123
如果要调用 delete_instance()
,您最终会发出 1001 个查询。所以希望很清楚为什么以这种方式实现它。
我建议如果您要删除行 并且 需要对相关行执行某种清理,那么您最好进行软删除(例如, 设置一个 status=DELETED
).然后处理信号 API.
之外的任何关系
我看到peewee有信号http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#signals
但它只适用于 delete_instance()
。
For what I hope are obvious reasons, Peewee signals do not work when you use the Model.insert(), Model.update(), or Model.delete() methods. These methods generate queries that execute beyond the scope of the ORM, and the ORM does not know about which model instances might or might not be affected when the query executes.
Signals work by hooking into the higher-level peewee APIs like Model.save() and Model.delete_instance(), where the affected model instance is known ahead of time.
那么,既然信号对依赖性使用 delete()
,我该如何在依赖性记录上使用信号?
def delete_instance(self, recursive=False, delete_nullable=False):
if recursive:
dependencies = self.dependencies(delete_nullable)
for query, fk in reversed(list(dependencies)):
model = fk.model
if fk.null and not delete_nullable:
model.update(**{fk.name: None}).where(query).execute()
else:
model.delete().where(query).execute()
return type(self).delete().where(self._pk_expr()).execute()
简短的回答是你不能,因为递归删除是使用以下形式的查询实现的:
DELETE FROM ... WHERE foreign_key_id = X
例如,假设您有一个用户并且他们创建了 1000 条推文。 tweet.user_id 指向 user.id。当您删除该用户时,peewee 发出 2 个查询:
DELETE FROM tweets WHERE user_id = 123
DELETE FROM users WHERE id = 123
如果要调用 delete_instance()
,您最终会发出 1001 个查询。所以希望很清楚为什么以这种方式实现它。
我建议如果您要删除行 并且 需要对相关行执行某种清理,那么您最好进行软删除(例如, 设置一个 status=DELETED
).然后处理信号 API.