1

I have a django model which I want to keep the newest 40 objects from.

I have tried the following code to do this

delete = model.count() - 40
model.objects.all[:delete].delete()

I get the error "Cannot use 'limit' or 'offset' with delete." with this though.

Can anyone suggest a way to do this?

mmckinlay
  • 55
  • 5

1 Answers1

3

Not beautiful but it works:

ids = MyModel.objects.order_by("-pk").values_list("pk", flat=True)[:40]
MyModel.objects.exclude(pk__in=list(ids)).delete()
Stan
  • 8,710
  • 2
  • 29
  • 31