Django 3 : Deleting objects

Louis SanchezJuly 29th 2021, 8:08

Deleting a record

Step 1To delete a record in the database, we must use the delete() method. Removing items is easier than changing items, because the method is the same for a queryset as for the instances of models. An example of this is as follows

from myproject.models import UserProfile
profile = UserProfile.objects.get(id = 1)
profile.delete()

Step 2 : The code template

{% extends "base.html" %}
{% block title %}
  {{ action }}
{% endblock %}
{% block h1 %}
  {{ action }}
{% endblock %}
{% block content %}
  {% if all_user_profile|length > 0 %}
  <table>
    <thead>
      <tr>
        <td>ID</td>
        <td>Name</td>
      </tr>
    </thead>
    <tbody>
    {% for profile in all_user_profile %}
      <tr>
        <td>{{ profile.id }}</td>
        <td>{{ profile.name }}</td>
      </tr>
    {% endfor %}
    </tbody>
  </table>
  {% else %}
  <span>No data.</span>
  {% endif %}
{% endblock %}

Step 3 : Now start the development server with the python manage.py runserver command and open http://127.0.0.1:8000/page/ in your browser.

Deleting multiple records

Step 4 : To delete multiple records in one shot, you must use the delete() method with a queryset object type

from myproject.models import UserProfile
profile = UserProfile.objects.filter(name = "admin").delete()