DEV Community

Cover image for Django models: Deleting a record from a database - [DELETE]
Arno Pretorius
Arno Pretorius

Posted on

Django models: Deleting a record from a database - [DELETE]

What are Django models?
A Django model is a built-in feature that is used to create tables and fields. These tables and fields are used to represent data that can be managed and accessed with Django. Simply put, models define the structure of the data that is stored

Let's get started.
So, what we want to understand is how to delete records from our table of cars based on our model Car.


Our records at a glance

Image description


1) Deleting a record

Now let's say that you don't want to delete a record from Car, perhaps, you want to delete the first record that has data about a Ferrari that also happens to be red.

First of all, you would need to use the get() function along with one of the car parameters.

Moreover, the get function will search all the rows in the table and return the first result. In this case, we will search by type - ferrari.

Then we can simply delete that particular instance that we found with our get() function.

To delete the record we can invoke the delete() function.

Image description

The code below shows how we would delete a record:

# - views.py  

car = Car.objects.get(type='ferrari') 
car.delete()
Enter fullscreen mode Exit fullscreen mode

DONE! - We are now able to delete a record from our table.


A final note…
For those that are interested in learning Django from scratch, feel free to check out my latest course:

Python Django: Ultimate Beginners Course - 2022

Top comments (0)