0

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?

Alex Rothberg
  • 10,243
  • 13
  • 60
  • 120
  • Note that this is really inefficient; the point of the queryset delete method is that it does a single delete query against the db, whereas this will do one query per record. – Daniel Roseman Mar 18 '15 at 16:51
  • I understand but in this case the additional delete logic is expensive anyways. Also there are places in contrib that use the queryset so not catching the delete call causes issues for me. – Alex Rothberg Mar 18 '15 at 16:52

1 Answers1

2

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
    
catavaran
  • 44,703
  • 8
  • 98
  • 85