Understanding how to use Django models - the simple way.
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
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.
The code below shows how we would delete a record.
# - views.py car = Car.objects.get(type='ferrari') car.delete()
DONE! - We are now able to delete a record from our table.