[Django]-Delete multiple objects in django

364👍

You can delete any QuerySet you’d like. For example, to delete all blog posts with some Post model

Post.objects.all().delete()

and to delete any Post with a future publication date

Post.objects.filter(pub_date__gt=datetime.now()).delete()

You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.

EDIT:

Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForms and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.

0👍

I need to select the objects to delete with a form on a webpage.

Since each object has a unique id, one way to select items to delete is using the id.

Following implements an example where a button on a webpage passes off the id of an object to delete which is processed in the view.py file in a POST request.

views.py

from django.shortcuts import render
from .models import MyModel

def myview(request):
    # initialize some data to delete
    if request.method == 'GET': MyModel(name='John Doe', score=83).save()

    # delete object with the id that was passed in the post request
    if request.method == 'POST':
        if 'delete' in request.POST:
            try:
                # id of the object to delete
                key = request.POST['delete']
                # delete that object
                MyModel.objects.get(id=key).delete()
            except MyModel.DoesNotExist:
                pass
    scores = MyModel.objects.all()
    return render(request, 'mypage.html', {'scores': scores})

models.py

from django.db import models
class MyModel(models.Model):
    name = models.CharField(max_length=50)
    score = models.IntegerField()

urls.py

from django.urls import path
from .views import myview

urlpatterns = [
    path('mypage/', myview, name='mypage')
]

templates/mypage.html

<form method='post' action={% url 'mypage' %}>
    {% csrf_token %}
    {% for person in scores %}
        {{ person.name }} {{ person.score }}
        {% comment %} to differentiate entries, use id {% endcomment %}
        <button name='delete', value="{{person.id}}">Delete</button><br>
    {% endfor %}
</form>

It creates a webpage that looks like the following and when the Delete button is clicked, the entry for "John Doe" is deleted.

ex

Leave a comment