Skip to content
Advertisement

Is it possible to delete last n records of a django model in one/minimum database query?

I’m trying to delete last 10 records of Task table/model in django but I’m unable to do that in one query.

Task.objects.filter(type='Active').order_by('-id')[:10].delete() 

Above code gives me error AttributeError : ‘list’ object has no attribute ‘delete’. If I make a loop and then use .delete() on each object of that list then it will call db n times which I don’t want, is there any other way?

Advertisement

Answer

You can use the primary keys in the queryset to filter with pk__in=…:

Task.objects.filter(
    pk__in=Task.objects.filter(type='Active').order_by('-id').values('pk')[:10]
).delete() 
10 People found this is helpful
Advertisement