[Fixed]-How to delete first N items from queryset in django

30👍

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.

7👍

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)

1👍

Try this.
Loop through all filtered objects

delatable_objects = Model.objects.all()[:N]
for m in delatable_objects:
    m.delete()

1👍

You can loop through the queryset and apply delete method to the objects.

for obj in m:
    obj.delete()
👤Sam

Leave a comment