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 different types of table relationships in Django: one-to-one, one-to-many, and many-to-many.
Prerequisites:
Step 1: One-to-one relationship
1.1. In your Django app, open the models.py
file and create two models, User
and Profile
. We will use Django's OneToOneField
to create a one-to-one relationship between the two models:
from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField()
Step 2: One-to-many relationship
2.1. For a one-to-many relationship, we will use ForeignKey
. Let's create two new models, Author
and Book
, where an author can have multiple books, but each book can only have one author:
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)
Step 3: Many-to-many relationship
3.1. For a many-to-many relationship, we will use ManyToManyField
. Let's create two new models, Tag
and Article
, where an article can have multiple tags, and a tag can be associated with multiple articles:
class Tag(models.Model): name = models.CharField(max_length=100) class Article(models.Model): title = models.CharField(max_length=100) content = models.TextField() tags = models.ManyToManyField(Tag)
Now that we have created the models for each relationship type, let's go through some examples of how to use them:
Example: Creating and associating objects
# One-to-one relationship user = User.objects.create_user(username='john', password='johnpassword') profile = Profile.objects.create(user=user, bio='A software developer') # One-to-many relationship author = Author.objects.create(name='Jane Doe') book1 = Book.objects.create(title='Django for Beginners', author=author) book2 = Book.objects.create(title='Django for Professionals', author=author) # Many-to-many relationship tag1 = Tag.objects.create(name='django') tag2 = Tag.objects.create(name='python') article = Article.objects.create(title='Understanding Django', content='...') article.tags.add(tag1, tag2)
Example: Querying related objects
# One-to-one relationship user_profile = user.profile profile_user = profile.user # One-to-many relationship jane_books = author.book_set.all() # Many-to-many relationship article_tags = article.tags.all() django_tag_articles = tag1.article_set.all()
In this tutorial, we covered different types of table relationships in Django: one-to-one, one-to-many, and many-to-many. By defining relationships between your models, you can efficiently query and manage related data in your Django application.
Django one-to-many relationship examples:
# Parent model class Author(models.Model): name = models.CharField(max_length=100) # Child model class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(Author, on_delete=models.CASCADE)
Django ForeignKey
and OneToOneField
examples:
ForeignKey
establishes a many-to-one relationship, while OneToOneField
establishes a one-to-one relationship.class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(Author, on_delete=models.CASCADE) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField()
Django on_delete
options explained:
on_delete
specifies the behavior when the referenced object is deleted. Options include CASCADE
, PROTECT
, SET_NULL
, etc.class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True)
Django reverse relationships in models:
# Accessing reverse relationship author = Author.objects.get(id=1) books_by_author = author.book_set.all()
Django related_name
attribute in model relationships:
related_name
allows specifying a custom name for the reverse relation, providing a cleaner API.class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
Django querying related models with select_related()
:
select_related()
optimizes queries by fetching related objects in a single query instead of multiple queries.# Using select_related queryset = Book.objects.select_related('author')
Django prefetch_related()
for optimizing related queries:
prefetch_related()
optimizes queries by prefetching related objects, reducing the number of queries needed.# Using prefetch_related queryset = Author.objects.prefetch_related('books')
Django model inheritance and relationships:
class Person(models.Model): name = models.CharField(max_length=100) class Author(Person): bio = models.TextField() class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE)
Django model relationships and serializers:
class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = '__all__'
Django nested relationships in serializers:
class AuthorSerializer(serializers.ModelSerializer): books = BookSerializer(many=True, read_only=True) class Meta: model = Author fields = '__all__'