Stevy
Stevy

Reputation: 3387

Django admin bulk delete exclude certain queryset

I have a multiple objects of a File model.

I am trying filter and delete these files based on a certain condition but am failing to succeed in this.

Consider the following

I have 3 File objects:

I tried to override the delete() function of the model like this:

def delete(self, using=None, keep_parents=False):
    test_qs = File.objects.filter(file_name='File1')
    if test_qs:
        for x in test_qs:
            x.delete()
    super(File, self).delete()

When I go to my Django Admin, select all the files (File1, File2 & File3) and bulk delete them, all of them are deleted instead of just File1.

In my Django Console File.objects.filter(file_name='File1') returns a queryset with just File1.

I also tried to override the pre_delete signal like this:

@receiver(pre_delete, sender=File)
def delete_certain_files(sender, instance, **kwargs):
    test_qs = File.objects.filter(file_name='File1')
    test_qs.delete()

This however, results in a RecursionError

How do I make sure to just delete the File objects that meet a certain condition upon bulk deletion?

Upvotes: 0

Views: 835

Answers (1)

gachdavit
gachdavit

Reputation: 1261

So, If you want this on admin. Imagine we have Foo model and FooAdmin class

class FooAdmin(admin.ModelAdmin):

    actions = ['delete_selected']

    def delete_selected(self, request, queryset):
        # request: WSGIRrequest
        # queryset: QuerySet, this is used for deletion
        lookup_kwargs = {'pk__gt': 5000} # you can add your own condition.
        queryset.filter(**lookup_kwargs)

admin.site.register(Foo, FooAdmin)

Upvotes: 2

Related Questions