Reputation: 2431
How to delete specific number of entries from the database? I did something like this
EntriesToDelete=Statusmessages.objects.filter(time__lt=date)[:30000]
EntriesToDelete.delete()
But I get an error which says:
AssertionError. Cannot use 'limit' or 'offset' with delete
.
How can I specify the number of entries to be deleted.
Upvotes: 21
Views: 12490
Reputation: 33420
You could do it like this:
pks = (Statusmessages.objects
.filter(time__lt=date)
.values_list('pk')[:30000])
Statusmessages.objects.filter(pk__in=pks).delete()
Upvotes: 49
Reputation: 789
If you get the following error:
django.db.utils.NotSupportedError: (1235, "This version of MariaDB doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'")
Force evaluate the list of ids with list(). Here's an example:
sessions_to_delete = LoginSession.objects.filter(user=self.userProfile)[3:]
pks_of_sessions_to_delete = list(sessions_to_delete.values_list("pk", flat=True))
LoginSession.objects.filter(pk__in=pks_of_sessions_to_delete).delete()
Upvotes: 1
Reputation: 107
use this:
Statusmessages.objects.filter(pk__in=Statusmessages.objects.filter(time__lt=date).values_list('pk', flat=True)[:30000]).delete()
use flat=True
, if not then is a tuple and raise exception:
{NotSupportedError}(1235, "This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'")
Upvotes: 1