查询集上的自定义删除方法 [英] Custom delete method on queryset
问题描述
我的Django模型在 delete
方法中具有自定义逻辑。因此,由于我想确保在我调用此逻辑在我的 queryset
上调用delete,我编写了自己的 queryset
delete。
My Django model has custom logic in the delete
method. Therefore since I wane to make sure that this logic is called when I call delete on my queryset
, I wrote my own queryset
delete.
class MyQuerySet(QuerySet):
# Do we have to be any fancier here?
def delete(self):
for m in self:
m.delete()
,我的问题是,除了在每个实例上迭代并调用 delete
之外,我还需要做其他更有趣的事情吗?
and my question is do I have to do anything fancier than iterating and calling delete
on each instance?
推荐答案
您应该清除结果缓存,以便如果查询集将被重用,则将再次评估数据库查询。
You should clear the result cache so if the queryset will be reused then DB query will be evaluated again.
还必须设置两个属性:
-
alters_data = True
阻止调用此属性模板中的方法; -
queryset_only = True
从用作管理器的查询集中隐藏此方法。
alters_data=True
prevents calling this method from templates;queryset_only=True
hides this method from queryset used as manager.
类MyQuerySet(QuerySet):
class MyQuerySet(QuerySet):
def delete(self):
for m in self:
m.delete()
self._result_cache = None
delete.alters_data = True
delete.queryset_only = True
这篇关于查询集上的自定义删除方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!