Answer a question

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?

Answers

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.

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐