CRUD Operations with Django

CRUD Operations with Django

In Django, CRUD (Create, Read, Update, Delete) operations are used to interact with the database and perform various data manipulation tasks. Django’s built-in ORM (Object-Relational Mapping) provides a convenient way to handle these operations. Here’s a step-by-step guide on how to use CRUD operations with Django:

Assuming you have already set up a Django project and app, if not refer to this blog – Creating first Django Project  let’s create a simple model for a blog post as an example to demonstrate CRUD operations.

1. Create a Model: In your app’s models.py, define the model representing the blog post:

				
					from django.db import models

class BlogPost(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    pub_date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

				
			

 

 

 

2. Apply Database Migrations:

Run the following commands to create and apply the database migrations for the new model:

				
					python manage.py makemigrations
python manage.py migrate

				
			

 

 

 

3. Create Data (Create):

To create a new blog post, you can use the Django admin interface or create objects programmatically. Let’s create a blog post programmatically:

				
					from myapp.models import BlogPost

# Create a new blog post
new_post = BlogPost.objects.create(
    title='New Blog Post',
    content='This is the content of the new blog post.',
)

				
			

 

 

 

4. Read Data (Retrieve):

To retrieve data, you can use various query methods provided by Django’s ORM. For example, to get all blog posts or retrieve a specific post by its primary key (id):

				
					from myapp.models import BlogPost

# Get all blog posts
all_posts = BlogPost.objects.all()

# Get a specific post by its id
post = BlogPost.objects.get(pk=1)  # Replace 1 with the desired post's id

				
			

 

 

 

5. Update Data (Update):

To update an existing blog post, you can retrieve the object, modify its attributes, and then save it:

				
					from myapp.models import BlogPost

# Retrieve the post to update
post = BlogPost.objects.get(pk=1)

# Modify the attributes
post.title = 'Updated Blog Post Title'
post.content = 'This is the updated content.'

# Save the changes
post.save()

				
			

 

 

 

6. Delete Data (Delete):

To delete a blog post, retrieve the object and call its delete() method:

				
					from myapp.models import BlogPost

# Retrieve the post to delete
post = BlogPost.objects.get(pk=1)

# Delete the post
post.delete()

				
			

These are the basic CRUD operations you can perform with Django’s ORM. You can combine these operations with views and templates to build full-fledged web applications that interact with the database and provide a user-friendly interface for managing data.

Tech Amplifier Final Logo