DEV Community

Cover image for Django models: Updating a record from a database - [UPDATE]
Arno Pretorius
Arno Pretorius

Posted on

Django models: Updating a record from a database - [UPDATE]

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 update records from our table of cars based on our model Car.

Our records at a glance

Image description


1) Updating a record

Now let's say that you don't want to update a record from Car, perhaps, you want to update your 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 will need to choose the field of that record that we want to update. We will change the colour to yellow.

After we have set the change, we can then save the updated record, using the save() function.

Image description

The code below shows how we would update a record.

# - views.py

car = Car.objects.get(type='ferrari')
car.colour = 'yellow'
car.save()
Enter fullscreen mode Exit fullscreen mode

DONE! - We are now able to update records in 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)