Custom delete method on queryset

谁说胖子不能爱 提交于 2019-12-12 01:48:51

问题


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()

and my question is do I have to do anything fancier than iterating and calling delete on each instance?


回答1:


You should clear the result cache so if the queryset will be reused then DB query will be evaluated again.

Also you have to set two attributes:

  • alters_data=True prevents calling this method from templates;
  • queryset_only=True hides this method from queryset used as manager.

    class MyQuerySet(QuerySet):

    def delete(self):
        for m in self:
            m.delete()
        self._result_cache = None    
    delete.alters_data = True
    delete.queryset_only = True
    


来源:https://stackoverflow.com/questions/29127828/custom-delete-method-on-queryset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!