2. CRUD
Django provides an Object-Relational Mapper (ORM) that allows us to perform CRUD (Create, Read, Update, Delete) operations on database models easily.
1. Create (Insert Data)
Section titled “1. Create (Insert Data)”You can insert data using:
.save().create().bulk_create()
Using .save()
Section titled “Using .save()”from myapp.models import Post
post = Post(title="New Post", content="This is a new blog post.")post.save() # Saves data to the databaseUsing .create()
Section titled “Using .create()”Post.objects.create(title="Another Post", content="Created using create()")Using .bulk_create() (Multiple Inserts)
Section titled “Using .bulk_create() (Multiple Inserts)”Post.objects.bulk_create([ Post(title="Post 1", content="Content 1"), Post(title="Post 2", content="Content 2"),])2. Read (Retrieve Data)
Section titled “2. Read (Retrieve Data)”You can retrieve data using:
.all().filter().get().values().count()
Retrieve All Objects
Section titled “Retrieve All Objects”posts = Post.objects.all()for post in posts: print(post.title, post.content)Retrieve a Single Object
Section titled “Retrieve a Single Object”post = Post.objects.get(id=1) # Get the post with ID = 1print(post.title)⚠️
.get()raises an error if no object is found.
Filter Data (Retrieve Specific Records)
Section titled “Filter Data (Retrieve Specific Records)”posts = Post.objects.filter(title="New Post") # Filter by titleRetrieve Specific Fields Only
Section titled “Retrieve Specific Fields Only”posts = Post.objects.values('title', 'content') # Returns a dictionary-like QuerySetCount Records
Section titled “Count Records”count = Post.objects.count() # Count total number of records3. Update (Modify Existing Data)
Section titled “3. Update (Modify Existing Data)”You can update data using:
- Modify an object and call
.save() - Use
.update()for multiple records
Update a Single Object
Section titled “Update a Single Object”post = Post.objects.get(id=1)post.title = "Updated Title"post.save()Update Multiple Records at Once
Section titled “Update Multiple Records at Once”Post.objects.filter(title="Old Title").update(title="New Title")4. Delete (Remove Data)
Section titled “4. Delete (Remove Data)”You can delete data using:
.delete().filter().delete()for multiple records
Delete a Single Object
Section titled “Delete a Single Object”post = Post.objects.get(id=1)post.delete()Delete Multiple Objects
Section titled “Delete Multiple Objects”Post.objects.filter(title="Old Title").delete()Delete All Objects in a Model
Section titled “Delete All Objects in a Model”Post.objects.all().delete()5. Full CRUD Example
Section titled “5. Full CRUD Example”5.1 View for CRUD
Section titled “5.1 View for CRUD”from django.shortcuts import render, get_object_or_404, redirectfrom .models import Postfrom .forms import PostForm
# Create a new postdef create_post(request): if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): form.save() return redirect('post_list') # Redirect to post list else: form = PostForm() return render(request, 'blog/create_post.html', {'form': form})
# Read all postsdef post_list(request): posts = Post.objects.all() return render(request, 'blog/post_list.html', {'posts': posts})
# Update a postdef update_post(request, post_id): post = get_object_or_404(Post, id=post_id) if request.method == 'POST': form = PostForm(request.POST, instance=post) if form.is_valid(): form.save() return redirect('post_list') else: form = PostForm(instance=post) return render(request, 'blog/update_post.html', {'form': form})
# Delete a postdef delete_post(request, post_id): post = get_object_or_404(Post, id=post_id) if request.method == 'POST': post.delete() return redirect('post_list') return render(request, 'blog/delete_post.html', {'post': post})5.2 CRUD Templates
Section titled “5.2 CRUD Templates”Form for Creating and Updating Posts
Section titled “Form for Creating and Updating Posts”<form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button></form>List All Posts
Section titled “List All Posts”{% for post in posts %} <h2>{{ post.title }}</h2> <p>{{ post.content }}</p> <a href="{% url 'update_post' post.id %}">Edit</a> <a href="{% url 'delete_post' post.id %}">Delete</a>{% endfor %}Delete Confirmation
Section titled “Delete Confirmation”<form method="post"> {% csrf_token %} <p>Are you sure you want to delete "{{ post.title }}"?</p> <button type="submit">Yes, Delete</button></form>5.3 CRUD URLs
Section titled “5.3 CRUD URLs”from django.urls import pathfrom .views import create_post, post_list, update_post, delete_post
urlpatterns = [ path('', post_list, name='post_list'), path('create/', create_post, name='create_post'), path('update/<int:post_id>/', update_post, name='update_post'), path('delete/<int:post_id>/', delete_post, name='delete_post'),]