Skip to content

3. More on CRUD

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())

Section titled “1.1 Using Django ORM in Views (save(), create())”

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

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)
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)

Section titled “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.

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().

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

  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.

You can insert data interactively using the Django shell.

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

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

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

Section titled “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})
templates/blog/create_post.html
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>

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"])