Skip to content

3. More on CRUD

1. Inserting Data into Django Models

Django models are Python classes that represent database tables. You can insert data into models using different methods, such as Django ORM (save() method, create() method, and bulk_create()), Django Admin, or Django Shell.

1.1 Using Django ORM in Views (save(), create())

Django’s ORM (Object-Relational Mapper) lets you insert data without writing SQL queries.

1. save() Method (Manual Object Creation)

You create a model instance and call .save() to insert data into the database.

models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
Inserting Data Using save()
from blog.models import Post
post = Post(title="My First Post", content="This is the content of the first post.")
post.save() # Saves data to the database
  • First, an instance of the Post model is created.
  • Then, .save() inserts the record into the database.

2. create() Method (Shortcut for Inserting Data)

Django provides a shortcut to create and save an object in one step using .create().

Post.objects.create(title="My Second Post", content="This is another blog post.")
  • This creates and saves the object immediately.
  • No need to call .save() manually.

3. bulk_create() for Multiple Inserts

If you want to insert multiple records at once, use .bulk_create(), which is faster than multiple .save() calls.

Post.objects.bulk_create([
Post(title="Post 1", content="Content 1"),
Post(title="Post 2", content="Content 2"),
Post(title="Post 3", content="Content 3"),
])
  • This performs a single SQL query to insert multiple records.
  • Much more efficient than looping through .save().

1.2 Inserting Data Using Django Admin

Django Admin allows you to insert data via a web interface.

Steps to Enable Django Admin for a Model

  1. Register the Model in admin.py:
    from django.contrib import admin
    from .models import Post
    admin.site.register(Post) # Registers the model in the admin panel
  2. Run the Server and Add Data:
    • Start the server: python manage.py runserver
    • Visit: http://127.0.0.1:8000/admin/
    • Log in and add new records through the Django Admin panel.

1.3 Inserting Data Using Django Shell

You can insert data interactively using the Django shell.

Open Django Shell

Terminal window
python manage.py shell

Insert a Record in the Shell

from blog.models import Post
post = Post(title="Shell Post", content="Inserted via Django shell")
post.save()

1.4 Inserting Data Using Forms

If you want to insert data via a web form, use Django ModelForms.

1. Create a Django Form (forms.py)

from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'content']

2. Create a View to Handle Form Submission

views.py
from django.shortcuts import render, redirect
from .forms import PostForm
def create_post(request):
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
form.save()
return redirect('post_list') # Redirect to a page after saving
else:
form = PostForm()
return render(request, 'blog/create_post.html', {'form': form})

3. Create a Template

templates/blog/create_post.html
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>

1.5 Inserting Data with Raw SQL Queries

Although Django’s ORM is preferred, you can use raw SQL if needed.

from django.db import connection
with connection.cursor() as cursor:
cursor.execute("INSERT INTO blog_post (title, content, created_at) VALUES (%s, %s, NOW())",
["SQL Post", "Inserted via raw SQL"])