How to insert, update and delete in Django models

Django is a high-level web framework written in Python that allows developers to build web applications quickly and efficiently. It follows the Model-Template-View (MTV) architectural pattern.

What are Django models?

In a website, it is important to gain information from a user, store it in a database, and retrieve the data from the database for further processing. In Django, we use models to incorporate a database into a Django project.

Models define the structure of the data stored in a database, including the field types, possibly their maximum size or default values, etc. A model in Django is a Python class that generally maps to a single database table. Django already comes equipped with SQLite.

Operations on Django models

In Django, performing operations like the CRUD (create, read, update, delete) operations on models is straightforward due to the built-in object-relational mapping (ORM) system. n this case, the CRUD operations are applied to the database.

Creating a Django model

To create a Model, we use a class structure inside of the relevant application’s models.py file that already exists in our application’s directory.

This class object will be a subclass of Django’s built-in class.

django.db.models.Model
django models

In the models.py file of your app (myapp/models.py), define your model. For a basic example, let's create an employee model with basic fields.

from django.db import models
class Employee(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField(unique=True)
job_title = models.CharField(max_length=100)
Creating a model in django

This creates a table in SQLite with the table name, Employee, and the attributes first_name, last_name, email, and job_title. The table will be created once you run the migrate and makemigrations commands.

Inserting in a Django model

To insert values into the Employee table using Django, we can use the Python shell with the shell command. This allows us to create the Employee objects and save them to the database.

Here's a basic example of how to insert values into the Employee table:

# Import the Employee model
from your_app.models import Employee
# Create an Employee object and set its attributes
employee1 = Employee(first_name='John', last_name='Doe', email='john.doe@example.com', job_title='Software Engineer')
employee2 = Employee(first_name='Jane', last_name='Smith', email='jane.smith@example.com', job_title='Product Manager')
# Save the Employee objects to the database
employee1.save()
employee2.save()

With the above code, two Employee records will be inserted into the database with the provided values. You can create more Employee objects and save them in a similar manner to insert additional records

Updating a record in the Django model

To update a record in the Django model, we follow these steps:

  1. Retrieve the record that you want to update.

  2. Update the attributes of the retrieved record.

  3. Save the changes to the database.

Here's the sample code to update a Django model:

# Import the Employee model
from your_app.models import Employee
x=Employee.objects.all()[1]
x.first_name='Mark'
x.save()

Code explanation

Line 3: x = Employee.objects.all()[1] retrieves all Employee records from the database using objects.all(). The query set returned by all() contains all the records in the table. Then, you use indexing [1] to get the second record (index 1) from the query set.

Line 4: x.first_name = 'Mark' updates the first_name attribute of the Employee record retrieved in the previous step to 'Mark'.

Line 5: x.save() saves the changes made to the x object.

Deleting a record in a Django model

To delete a record from the Employee table using Django's ORM, you can follow these steps:

  1. Retrieve the record you want to delete.

  2. Call the delete() method on the retrieved record.

Here's an example of how to delete an existing record from the Employee table:

# Import the Employee model
from your_app.models import Employee
x=Employee.objects.all()[1]
x.delete()

The first few lines of code are similar to the code lines in updating records, such as x = Employee.objects.all()[1] gets the second employee from the Employee table. x.delete() deletes the Employee record referenced by the x object from the database. The delete() method removes the record from the database permanently. After running this code, the Employee record at index 1 (a second record) will be deleted from the database.

Conclusion

In conclusion, Django's object-relational mapping (ORM) makes it significantly easier to interact with databases in web applications. Instead of writing raw SQL queries, developers can define Django models as Python classes, which act as abstractions over the underlying database tables. The ORM handles the translation between Python code and SQL queries, making database operations more intuitive and less error-prone.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved