Skip to content Skip to sidebar Skip to footer

How Can I Deal With A Massive Delete From Django Admin?

I'm working with Django 2.2.10. I have a model called Site, and a model called Record. Each record is associated with a single site (Foreign Key). After my app runs for a few days/

Solution 1:

Add this to your admin class, and than you can delete with this action without warning

  actions = ["silent_delete"]

  defsilent_delete(self, request, queryset):
    queryset.delete()

If you want to hide default delete action, add this to your admin class

defget_actions(self, request):
    actions = super().get_actions(request)
    if'delete_selected'in actions:
      del actions['delete_selected']
    return actions

Solution 2:

Since django 2.1 you can override get_deleted_objects to limit the amount of deleted objects listed (it's either a list or a nested list). The timeout is probably due to the django app server timing out on the view's response.

You could limit the size of the returned list:

classYourModelAdmin(django.admin.ModelAdmin):

    defget_deleted_objects(self, objs, request):
        deleted = super().get_deleted_objects(objs, request)
        deleted_objs = deleted[0]
        return (self.__limit_nested(deleted_objs),) + deleted[1:]

    def__limit_nested(self, objs):
        limit = 10ifisinstance(objs, list):
            returnlist(map(self.__limit_nested, objs))
        iflen(objs) > limit:
            return objs[:limit] + ['...']
        return objs

But chances are the call to super takes too long as well, so you probably want to return [], {}, set(), [] instead of calling super; though it doesn't tell you about missing permissions or protected relations then (but I saw no alternative other than copy pasting code from django github). You will want to override the delete_confirmation.html and the delete_selected_confirmation.html template as well. You'll also want to make sure the admin has permission to delete any related objects that might get deleted by the cascading deletes.

In fact, the deletion itself may take too long. It's probably best defer the deletion (and permission checks if those are slow too) to a celery task.

Post a Comment for "How Can I Deal With A Massive Delete From Django Admin?"