Django Insert Data
Adding new records to your database
➕ What is Inserting Data?
Inserting data means adding new records to your database. Django provides simple methods to create and save new objects using your model classes.
# Create a new product
product = Product(name='Laptop', price=999.99)
product.save()
Key Insert Methods
Create & Save
Create object then save it
obj = Model()
obj.save()
Create Method
Create and save in one step
Model.objects.create()
Bulk Create
Insert multiple records at once
Model.objects.bulk_create()
Get or Create
Create only if doesn't exist
Model.objects.get_or_create()
🔹 Method 1: Create and Save
Create an instance of your model, set its attributes, then save it to the database. This is the most basic way to insert data.
# models.py
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.IntegerField()
# Insert data
product = Product()
product.name = 'Laptop'
product.price = 999.99
product.stock = 50
product.save() # Saves to database
print(f"Product {product.name} created with ID: {product.id}")
Output:
Product Laptop created with ID: 1
🔹 Method 2: Create with Constructor
Pass field values directly to the constructor:
# Create product with constructor
product = Product(
name='Mouse',
price=29.99,
stock=100
)
product.save()
print(f"Created: {product.name} - ${product.price}")
Output:
Created: Mouse - $29.99
🔹 Method 3: Using create() Method
Create and save in one step using the create() method:
# Create and save in one line
product = Product.objects.create(
name='Keyboard',
price=79.99,
stock=75
)
# No need to call save() - it's automatic!
print(f"Product ID {product.id}: {product.name}")
Output:
Product ID 3: Keyboard
🔹 Inserting Multiple Records
Use bulk_create() to insert many records efficiently:
# Create multiple products at once
products = [
Product(name='Monitor', price=299.99, stock=30),
Product(name='Webcam', price=89.99, stock=45),
Product(name='Headset', price=59.99, stock=60),
]
# Bulk insert
Product.objects.bulk_create(products)
print(f"Inserted {len(products)} products")
Output:
Inserted 3 products
🔹 Get or Create
Create a record only if it doesn't already exist:
# Get existing or create new
product, created = Product.objects.get_or_create(
name='Laptop',
defaults={
'price': 999.99,
'stock': 50
}
)
if created:
print(f"Created new product: {product.name}")
else:
print(f"Product already exists: {product.name}")
Output (if new):
Created new product: Laptop
🔹 Inserting with Relationships
Insert data with foreign key relationships:
from django.contrib.auth.models import User
class BlogPost(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
# Get or create user
user = User.objects.get(username='john')
# Create blog post with relationship
post = BlogPost.objects.create(
title='My First Post',
content='This is my first blog post!',
author=user
)
print(f"Post '{post.title}' by {post.author.username}")
Output:
Post 'My First Post' by john
🔹 Inserting from Forms
Insert data from user input using forms:
# views.py
from django.shortcuts import render, redirect
from .models import Product
def add_product(request):
if request.method == 'POST':
# Get data from form
name = request.POST.get('name')
price = request.POST.get('price')
stock = request.POST.get('stock')
# Create product
Product.objects.create(
name=name,
price=price,
stock=stock
)
return redirect('product_list')
return render(request, 'add_product.html')
<!-- templates/add_product.html -->
<form method="post">
{% csrf_token %}
<input type="text" name="name" placeholder="Product Name">
<input type="number" name="price" step="0.01" placeholder="Price">
<input type="number" name="stock" placeholder="Stock">
<button type="submit">Add Product</button>
</form>