30👍
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.
7👍
You don’t have the option directly. So you should delete it by some advanced ways. For example:
not_ideal = Model.objects.all()[N:].values_list("id", flat=True)
Model.objects.exclude(pk__in=list(not_ideal)).delete()
Using this way you are finding your not ideal objects and delete everything except them.
You can use anything beside id
. But id is unique and will help you to optimize.
Notice that in the first line I’m getting the items which are from N
to the last
.(Not from the first
to N
)
- Redirect request to admin interface
- Django File Upload and Rename
- How to make sure Django models match the database schema
- How to correctly use auto_created attribute in django?
- Django is very slow on my machine
1👍
Try this.
Loop through all filtered objects
delatable_objects = Model.objects.all()[:N]
for m in delatable_objects:
m.delete()
1👍
You can loop through the queryset and apply delete method to the objects.
for obj in m:
obj.delete()
- Django crispy forms: Nesting a formset within a form
- Filter on datetime closest to the given datetime
- Django: duplicates when filtering on many to many field
- Django REST – Create object with foreign key using serializers