[Django]-Override delete_selected() and update fields of child model

8👍

While this answer works, if you delete a single obj anywhere else in your code, the delete_model method will throw an error.

I recommend this:

actions = ['delete_selected']

def delete_selected(self, request, obj):
    for o in obj.all():
        Action.objects.filter(invoice=o).update(billed=False)
        o.delete()

delete_selected.short_description = 'Ausgewählte Rechnungen löschen'

Just override the delete_selected action for the Change List admin page. This way you’re not having to completely delete the action, override the delete_model method, and as a plus, you can still delete individual items from the Change <object> admin page. In the long run it’s less code. 🙂

7👍

I HAVE FOUND A SOLUTION, postet y Stephane https://stackoverflow.com/a/4534773/326905 and edited it for my issue.

The correct action is delete_selected
In admin.py under the InvoiceAdmin Model

actions = ['delete_model']

def get_actions(self, request):
    actions = super(InvoiceAdmin, self).get_actions(request)
    del actions['delete_selected']
    return actions

def delete_model(self, request, obj):
    for o in obj.all():
        Action.objects.filter(invoice=o).update(billed=False)
        o.delete()

delete_model.short_description = 'Ausgewählte Rechnungen löschen'
👤surfi

Leave a comment