
{{ $('Map tags to IDs').item.json.title }}
Using Django ORM for Database Queries
Django’s Object-Relational Mapping (ORM) allows you to interact with your database using Python code instead of raw SQL queries. This tutorial will guide you through the basics of using Django ORM for database queries in your applications.
Prerequisites
- Basic understanding of Python and Django.
- A Django project set up with a configured database.
1. Setting Up Your Models
Before you can use Django ORM, you need to define your data models. Open your models.py
file in your Django app and create your models. For example:
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
published_date = models.DateField()
After defining your models, run:
python manage.py makemigrations
python manage.py migrate
This creates the necessary database tables.
2. Querying the Database
Django ORM provides a powerful API for querying the database. You can perform various queries as shown below:
2.1. Creating Records
To create new objects, use the create()
method:
new_author = Author.objects.create(name='J.K. Rowling', email='[email protected]')
2.2. Retrieving Records
You can retrieve records using different methods:
- All Records:
authors = Author.objects.all()
- Filtering Records:
jk_rowling = Author.objects.filter(name='J.K. Rowling')
- Getting a Single Record:
first_author = Author.objects.get(id=1)
2.3. Updating Records
To update an existing record:
jk_rowling = Author.objects.get(name='J.K. Rowling')
jk_rowling.email = '[email protected]'
jk_rowling.save()
2.4. Deleting Records
To delete a record:
jk_rowling.delete()
3. Advanced Queries
Django ORM also supports advanced querying features:
- Ordering:
ordered_authors = Author.objects.order_by('name')
- Aggregation:
from django.db.models import Count num_books = Book.objects.filter(author=jk_rowling).count()
4. Using Querysets
Django’s QuerySets allow you to chain queries and lazy-load results. For example:
books = Book.objects.filter(author__name='J.K. Rowling').order_by('published_date')
This returns all books by the author and orders them by the published date.
5. Conclusion
Django ORM provides a powerful and flexible way to interact with your database. By following this guide, you can effectively use Django’s ORM for managing your database operations. As you dive deeper into Django, explore its additional capabilities and best practices to enhance your application’s performance and maintainability.