Filtering, Updating, and Deleting Records in Django


Django's ORM provides an intuitive way to work with database records. This article explains how to filter, update, and delete records using Django models.

Filtering Records

Filtering allows you to retrieve specific records based on certain conditions. Let's consider the following model:

            
    from django.db import models

    class Product(models.Model):
        name = models.CharField(max_length=100)
        category = models.CharField(max_length=50)
        price = models.DecimalField(max_digits=8, decimal_places=2)
        stock = models.IntegerField()
        available = models.BooleanField(default=True)

        def __str__(self):
            return self.name
            
        

Basic Filtering

Use the filter() method to retrieve records that match specific criteria:

            
    from myapp.models import Product

    # Filter products by category
    electronics = Product.objects.filter(category="Electronics")
    for product in electronics:
        print(product.name)
            
        

Field Lookups

Django provides field lookups for complex filtering:

            
    # Filter products with price less than 100
    cheap_products = Product.objects.filter(price__lt=100)

    # Filter products with name containing "phone" (case-insensitive)
    phones = Product.objects.filter(name__icontains="phone")

    # Filter available products
    available_products = Product.objects.filter(available=True)
            
        

Chaining Filters

You can chain multiple filters for complex queries:

            
    # Filter available electronics priced under 500
    affordable_electronics = Product.objects.filter(category="Electronics", available=True, price__lt=500)
            
        

Excluding Records

Use exclude() to exclude records that match specific conditions:

            
    # Exclude out-of-stock products
    in_stock_products = Product.objects.exclude(stock=0)
            
        

Updating Records

Django allows you to update records either individually or in bulk.

Updating a Single Record

Retrieve a record, modify its attributes, and save it:

            
    # Retrieve and update a product
    product = Product.objects.get(id=1)
    product.price = 120.00
    product.save()
            
        

Updating Multiple Records

Use update() to update multiple records in a single query:

            
    # Increase the price of all electronics by 10%
    Product.objects.filter(category="Electronics").update(price=F('price') * 1.1)
            
        

Deleting Records

Django provides methods for deleting records individually or in bulk.

Deleting a Single Record

Retrieve a record and use the delete() method:

            
    # Retrieve and delete a product
    product = Product.objects.get(id=1)
    product.delete()
            
        

Deleting Multiple Records

Use filter() to identify the records to delete and call delete():

            
    # Delete all out-of-stock products
    Product.objects.filter(stock=0).delete()
            
        

Important Notes

  • Using delete() is irreversible, so ensure the query matches the correct records.
  • Use Django's querysets efficiently to minimize database load for large datasets.

Conclusion

Filtering, updating, and deleting records are essential operations when working with databases in Django. By leveraging Django's ORM, you can perform these actions in a Pythonic and efficient manner.





Advertisement