How to Implement Join Operations in Django ORM

You will probably need to work with a database at some point if you are using Django to create a web application. 

Django Object Relational Mapping(ORM), makes this process easier by allowing you to work with Python classes instead of SQL queries.

Joining two or more tables to extract relevant data is one of the most common tasks when working with a database. We will look into joining tables with Django ORM in this tutorial.

Database Relationships

Before we dig into joining tables, it is essential to understand the different types of relationships that can exist between tables in a database. The three most common types of relationships are.

  • One-to-one(1:1)  – Each record in one table is related to one and only one record in another table.
  • One-to-many(1:N) – Each record in one table is related to zero, one, or many records in another table.
  • Many-to-Many(N: N) – Each record in one table is related to zero, one, or many records in another table and vice versa.

Create Django Join

Create a Project

First, we need to create a project by running the following commands in your terminal or command prompt

Django-admin startproject Joins_ORM

Create an app

A Django project consists of one or more apps. Creating a new app by running the following command in your terminal or command prompt

Python manage.py startapp jointable

Create a Model

from django.db import models

# Create your models here.

class Author(models.Model):
    FirstName = models.CharField(max_length=100)
    LastName = models.CharField(max_length=100)
    MiddleName = models.CharField(max_length=100)

class Books(models.Model):
    title = models.CharField(max_length=200)
    total_page = models.IntegerField()
    auth_id = models.ForeignKey(Author, on_delete=models. CASCADE)
    

Django Join Tables Using ORM

INNER JOIN

from django.shortcuts import render
from .models import Books,Author

# Create your views here.

def jointable(request):
    books = Books.objects.select_related('auth_id').filter(title='A Better World')

    return render(request,'index.html',{'context':books})

LEFT JOIN

def Leftjoin(request):

    books = Books.objects.filter(Q(auth_id__isnull=True)|Q(auth_id__isnull=False))   
    return render(request,'index.html',{'context':books})

RIGHT JOIN

def Rightjoin(request):

    books = Books.objects.select_related('auth_id').all()

    return render(request,'index.html',{'context':books})

See More How to Add Pagination

3.2 18 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments