Django Tutorial
Django Create A Complete Project
Django Template
Django Database Query
Django Form
Django Authentication and Permission Management
Django unittest
Django Advanced
In this tutorial, we will cover basic query operations to interact with the database using Django's Object-Relational Mapping (ORM).
Prerequisites:
Assuming we have an app named 'myapp' with the following models.py
:
from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE) publication_date = models.DateField() price = models.DecimalField(max_digits=5, decimal_places=2)
To create a new record in the database, you can use the create
method or instantiate the model and call the save
method.
Example:
from myapp.models import Author, Book from datetime import date # Using the create method author = Author.objects.create(name="John Doe") # Instantiating the model and calling save book = Book(title="Sample Book", author=author, publication_date=date.today(), price=9.99) book.save()
To fetch records from the database, you can use various methods provided by the ORM, such as all
, get
, filter
, and exclude
.
Example:
# Fetch all records all_books = Book.objects.all() # Fetch a single record based on a unique field author = Author.objects.get(name="John Doe") # Fetch records based on a condition books_by_john_doe = Book.objects.filter(author=author) # Fetch records excluding a condition books_not_by_john_doe = Book.objects.exclude(author=author)
To update a record, fetch it from the database, modify the fields, and call the save
method.
Example:
# Fetch a single record book = Book.objects.get(title="Sample Book") # Modify the field and save book.price = 12.99 book.save()
You can also use the update
method to update multiple records in a single query:
books_by_john_doe.update(price=14.99)
To delete a record, fetch it from the database and call the delete
method.
Example:
# Fetch a single record book = Book.objects.get(title="Sample Book") # Delete the record book.delete()
Django's ORM allows you to chain methods to create more complex queries.
Example:
# Fetch books published in 2022 and priced below $20 from datetime import date books = Book.objects.filter(publication_date__year=2022, price__lt=20)
In this tutorial, we covered basic database operations using Django's ORM. By using the ORM, you can interact with your database in a Pythonic way without writing raw SQL queries, making your code more maintainable and easier to understand.
Django database queries examples:
# Creating a new record new_instance = MyModel(field1='value1', field2='value2') new_instance.save() # Retrieving records all_records = MyModel.objects.all() # Updating a record record_to_update = MyModel.objects.get(id=1) record_to_update.field1 = 'new_value' record_to_update.save() # Deleting a record record_to_delete = MyModel.objects.get(id=1) record_to_delete.delete()
Django filter()
function examples:
filter()
method is used to narrow down query results based on specified conditions.# Basic filter queryset = MyModel.objects.filter(field1='value1') # Multiple conditions queryset = MyModel.objects.filter(field1='value1', field2__gt=10) # Case-insensitive filter queryset = MyModel.objects.filter(field1__iexact='value1')
Django model queries examples:
# Get a single record instance = MyModel.objects.get(id=1) # Get the first record first_instance = MyModel.objects.first() # Get the count of records record_count = MyModel.objects.count()
Django annotate()
and aggregate()
examples:
annotate()
is used to add extra fields to each object in the queryset, and aggregate()
is used to perform aggregate functions on the entire queryset.from django.db.models import Count, Sum # Annotate example queryset = MyModel.objects.annotate(comment_count=Count('comments')) # Aggregate example total_likes = MyModel.objects.aggregate(total_likes=Sum('likes'))
Django querying related models:
# Accessing related objects author = Author.objects.get(name='John Doe') books_by_author = author.book_set.all() # Reverse relationships book = Book.objects.get(title='My Book') author_of_book = book.author
Django complex queries examples:
from django.db.models import Q # Complex query using Q objects queryset = MyModel.objects.filter(Q(field1='value1') | Q(field2='value2'))
Django select_related()
and prefetch_related()
examples:
# select_related example queryset = MyModel.objects.select_related('related_model') # prefetch_related example queryset = MyModel.objects.prefetch_related('related_models')
Django bulk create and update operations:
# Bulk create MyModel.objects.bulk_create([MyModel(field1='value1'), MyModel(field1='value2')]) # Bulk update MyModel.objects.filter(field1='old_value').update(field1='new_value')
Advanced Django database querying techniques:
from django.db.models import F, Case, When # F expressions queryset = MyModel.objects.filter(counter__gt=F('threshold')) # Conditional expressions queryset = MyModel.objects.annotate(status=Case(When(condition=True, then='active', default='inactive')))