Mastering Django Framework: Building Scalable Web Applications
Course Title: Mastering Django Framework: Building Scalable Web Applications Section Title: Models and Database Operations Topic: Create models for a blog application, manage migrations, and perform CRUD operations.(Lab topic)
Objective: By the end of this topic, you will be able to create models for a blog application, manage migrations, and perform CRUD (Create, Read, Update, Delete) operations using Django's ORM.
Prerequisites:
- You have completed the previous topics in the Models and Database Operations section.
- You have a basic understanding of Django's ORM and database schema design.
Step 1: Create Models for a Blog Application
In this step, we will create models for a blog application. We will define two models: BlogPost
and Comment
.
# models.py
from django.db import models
class BlogPost(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
class Comment(models.Model):
blog_post = models.ForeignKey(BlogPost, on_delete=models.CASCADE)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
Step 2: Manage Migrations
After creating our models, we need to manage migrations to create the corresponding tables in the database.
# Create migrations
python manage.py makemigrations
# Apply migrations
python manage.py migrate
Step 3: Perform CRUD Operations
Now that we have our models and migrations in place, we can perform CRUD operations using Django's ORM.
Create
To create a new blog post, we can use the BlogPost
model's create
method.
# Create a new blog post
blog_post = BlogPost.objects.create(
title='My First Blog Post',
content='This is my first blog post.'
)
Read
To read a blog post, we can use the BlogPost
model's get
method.
# Get a blog post by ID
blog_post = BlogPost.objects.get(id=1)
print(blog_post.title) # Output: My First Blog Post
Update
To update a blog post, we can use the BlogPost
model's update
method.
# Update a blog post
blog_post = BlogPost.objects.get(id=1)
blog_post.title = 'My Updated Blog Post'
blog_post.save()
Delete
To delete a blog post, we can use the BlogPost
model's delete
method.
# Delete a blog post
blog_post = BlogPost.objects.get(id=1)
blog_post.delete()
Conclusion:
In this topic, we created models for a blog application, managed migrations, and performed CRUD operations using Django's ORM. We also learned how to use Django's ORM to interact with the database.
Additional Resources:
- Django documentation: Models
- Django documentation: Migrations
- Django documentation: ORM
Leave a comment or ask for help if you have any questions or need further clarification on any of the concepts covered in this topic.
Images

Comments