pythondjangodjango-rest-frameworkdjango-queryset

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?


Solution

  • 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(
        pk__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(…) [Django-doc] part to delete those items in bulk.