Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete first N items from queryset in django

I'm looking to delete only the first N results returned from a query in django. Following the django examples here which I found while reading this SO answer, I was able to limit the resulting set using the following code

m = Model.objects.all()[:N]

but attempting to delete it generates the following error

m.delete()
AssertionError: Cannot use 'limit' or 'offset' with delete.

Is there a way to accomplish this in django?

like image 448
Bash Avatar asked Jul 23 '19 15:07

Bash


2 Answers

You don't have the option directly. So you should delete it by some advanced ways. For example:

not_ideal = Model.objects.all()[N:].values_list("id", flat=True)
Model.objects.exclude(pk__in=list(not_ideal)).delete()

Using this way you are finding your not ideal objects and delete everything except them. You can use anything beside id. But id is unique and will help you to optimize.

Notice that in the first line I'm getting the items which are from N to the last.(Not from the first to N)

like image 113
Alireza HI Avatar answered Sep 28 '22 01:09

Alireza HI


You can not delete through a limit. Most databases do not support this.

You can however accomplish this in two steps, like:

Model.objects.filter(id__in=list(Models.objects.values_list('pk', flat=True)[:N])).delete()

We thus first retrieve the primary keys of the first N elements, and then use this in a .filter(..) part to delete those items in bulk.

like image 32
Willem Van Onsem Avatar answered Sep 28 '22 02:09

Willem Van Onsem