Union operation on models Django

In this Python Django Tutorial, I will show you how to perform union operations on models Django.

You will understand how to perform union operations on querysets that belong to the same model. Also, you will learn how to perform union operations on query sets that belong to different models.

Union operation on models Django

So ‘what is a union operation?’, from a mathematics point of view, suppose you have two sets A = [2,3 5,7] and B = [1,4,5,6]. To perform union between these sets, the symbol U is used like this ‘A’ U ‘B’.

The result of the union is a set [1,2,3,4,5,6,7] that contains all the elements from sets A and B except the duplicate.

If you see both sets, they have a common element which is 5 but this element is included only one time in the final set after performing the union operation.

Like that Django supports Set Operations that can be performed on the models. Set Operations are used to get meaningful results from the field stored in the models, under different special conditions.

Now, you will learn one of the Set Operations, called Union Operation. But where you will use the union operation in Django, well the answer is simple. You will use the union with Django Queryset.

Suppose you have a model related to the blog and you want to fetch the blog based on different categories. Then to combine these two separate query set into a single queryset, use the union operation.

Now you can say union operation in Django allows us to combine multiple queryset into a single queryset.

The Union Operation can be applied on the same or different models. The fields and data types should match when querysets are from distinct models or even from the same model.

Also, check: How to Create model in Django

Union Operation on the Same Model Using Django

I hope that you have a clear understanding of what Union Operation is. Let’s now turn our attention to the practical implementation of union operations.

Let’s learn how to use the union operation on the same model

Before starting the demonstration, I’ll show you the model and explain how to create it. For that open the terminal and create a virtual environment named ‘env_union’.

python -m venv env_union

Then activate the environment using the below code.

env_union\Scripts\activate

Install the latest version of Django.

pip install django

Create a Django project named ‘django_union’ using the below code.

django-admin startproject django_union

Change the directory to django_union.

cd django_union

Then create a Django app named ‘union_app’ using the below code.

python manage.py startapp union_app
Union Operation on Same Model Using Django Project Setup

Now open the Django project in your preferred IDE such as Visual Studio Code.

Firstly, create the model named ‘Employee’ in the model.py file of the Django app ‘union_app’ and add the following lines of code.

from django.db import models

class Employee(models.Model):
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    position = models.CharField(max_length=100)
    age = models.PositiveIntegerField()
    
    def __str__(self):  
        return "%s %s %s %s" % (self.first_name, self.last_name, self.position, self.age)  
Union Operation on Same Model Employee Using Django

In the above code define the model named Employee with field lists first_name, last_name, position of type CharField, and age of type PositiveIntegerField.

Next, register the Employee model by writing the below code in the admin.py file of your Django app ‘union_app’.

from django.contrib import admin
from .models import Employee

class AdminEmployee(admin.ModelAdmin):
    list_display = ['first_name', 'last_name', 'position', 'age']

admin.site.register(Employee, AdminEmployee)
Union Operation on Same Model Using Django Registering Model

Include your app in the INSTALLED_APPS list in your setting.py file of the Django project ‘django_union’.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'union_app'
]
Union Operation on Same Model Using Django Installing App

Now, run the below commands one by one to make a migration file.

python manage.py makemigrations
python manage.py migrate
Union Operation on Same Model Using Django Migration

Open the Python shell by writing the below command in your terminal.

python manage.py shell
Python Shell Union Operation on Same Model Using Django

Now use the below command in your Python shell and create some records related to the Employee.

from union_app.models import Employee
emp = Employee.objects.create(first_name = "Maria", last_name = "Ted", position = "Developer", age = "28")
Python Shell Union Operation on Same Model Creating Employee

You can use the above code to create multiple employee records in the database.

In this example, you will perform a Union Operation on the same model. So write the below code in your terminal.

# Import

from union_app.models import Employee

# QuerySet

queryset1 = Employee.objects.filter(age__gt=28)
queryset1

queryset2 = Employee.objects.filter(first_name="Maria")
queryset2

# Union Operation

queryset1.union(queryset2)
union operation on models python django

In the above code first import the model Employee from the file models.py of your Django app ‘union_app’.

  • Then retrieve all the employees from the database as queryset whose age is greater than 28 using the Employee.objects.filter(age__gt=28) where age__gt means age greater than.
  • Again retrieve the employee objects whose first name is Maria using the Employee.objects.filter(first_name=”Maria”)
  • Finally, the code queryset1.union(queryset2) performs the union operation on queryset1 and queryset2, and the result of the operation is a new queryset containing all unique Employee objects that either have an age greater than 28 or a first name equal to Maria.

Let’s take on more examples where you are going to perform Union Operation on Model Fileds position and last_name.

# Import

from union_app.models import Employee

# QuerySet

queryset1 = Employee.objects.filter(position="Vice President")
queryset1

queryset2 = Employee.objects.filter(last_name="Johnson")
queryset2

# Union Operation

queryset1.union(queryset2)
union operation on same model using django

In the above code retrieving the records from the database using the filter() method based on the model field names such as Position is Vice President and Last_Name is Johnson.

  • After that storing the retrieved querysets or objects to the corresponding variable queryset1 and queryset2.
  • Finally, the code queryset2.union(queryset1) performs the union operation on queryset2 and queryset1, and the result of the operation is a new queryset containing all unique Employee objects that either have position Vice President or a last name equal to Johnson.

So, if you want to get the duplicate values, use the all=True parameter with the union operation as shown below.

# Union Operation

queryset1.union(queryset2, all=True)
union operation on same model using python django

Read: Python Django vs ReactJS

Union Operation on different models using Django

Now you know how to perform union operations on queryset that belong to the same model. But in this section, you will learn how to use Union Operation on the different models. To better understand the concept, we’ll look at some examples.

Before starting the demonstration, I’ll show you the models and explain how to create them.

Firstly, open the models.py file of your Django app ‘myApp’ and create a Customer model by adding the following lines of code.

from django.db import models

# Create your models here.

class Customer(models.Model):
    Customer_Name = models.CharField(max_length=200)
    Customer_Contact_Name = models.CharField(max_length=200)
    Customer_Country = models.CharField(max_length=100)
    Customer_City = models.CharField(max_length=100)
    
    def __str__(self):  
        return "%s %s %s %s" % (self.Customer_Name, self.Customer_Contact_Name, self.Customer_Country, self.Customer_City) 

Next, we create a Supplier model.

from django.db import models

# Create your models here.

class Supplier(models.Model):
    Supplier_Name = models.CharField(max_length=200)
    Supplier_Contact_Name = models.CharField(max_length=200)
    Supplier_Country = models.CharField(max_length=100)
    Supplier_City = models.CharField(max_length=100)
    
    def __str__(self):  
        return "%s %s %s %s" % (self.Supplier_Name, self.Supplier_Contact_Name, self.Supplier_Country, self.Supplier_City) 
Union Operation on different models using Django

In the above code from lines 12 to 19 define the model named ‘ Customer’ that contains the field list Customer_Name, Customer_Contact_Name, Customer_Country, and Customer_City of type CharField.

After that from lines 21 to 28 define the model ‘Supplier’ with a field list Supplier_Name, Supplier_Contact_Name, Supplier_Country, and Supplier_City of type CharField

After the successful creation of models, register all the models in the admin.py file of your Django app ‘myApp’.

from django.contrib import admin
from .models import Customer
from .models import Supplier


class AdminCustomer(admin.ModelAdmin):
    list_display = ['Customer_Name', 'Customer_Contact_Name', 'Customer_Country', 'Customer_City']

class AdminSupplier(admin.ModelAdmin):
    list_display =  ['Supplier_Name', 'Supplier_Contact_Name', 'Supplier_Country', 'Supplier_City']

admin.site.register(Customer, AdminCustomer)
admin.site.register(Supplier, AdminSupplier)
Union Operation on different models using Django Register Model

Now take an example where you will learn how to perform union operations on querysets that belong to different models.

So run the following code in your Python shell.

# Import

from myApp.models.customer import Customer
from myApp.models.supplier import Supplier

# QuerySet

queryset1 = Customer.objects.filter(Customer_Country='UK')
queryset1

queryset2 = Supplier.objects.filter(Supplier_Country='UK')
queryset2

# Union Operation

queryset1.union(queryset2)
union operation on different models using django

In the above code, line 3 retrieves all the customer objects from the database that belong to the country “UK”. Then in line 5 retrieve all the supplier objects from the database that belong to the country “UK”.

Finally, line 7 performs a union operation on queryset1 and queryset2 to combine the objects of both queryset into a new queryset that contains all the unique customer or supplier objects that have a country equal to “UK”.

Here you should notice that the queryset1 and queryset2 are from the different models.

Let’s take one more example where you will perform the union operation on querysets that come from different models but are based on the primary key value.

Open the Python Shell and perform the Union Operation on different models.

# Import

from myApp.models.customer import Customer
from myApp.models.supplier import Supplier

# QuerySet

queryset1 = Customer.objects.filter(pk__in=[1, 2])
queryset1

queryset2 = Supplier.objects.filter(pk__in=[3])
queryset2

# Union Operation

queryset2.union(queryset1)
union operation on different models using python django

The above code does the following things:

  • Firstly we get the record from the Customer model based on the filter’s primary key values by using the querysets.
  • Then, we also get the record from the Supplier model on the basis of the filter primary key values by using the querysets.
  • Next, we use the Union Operation to get the record by combining both querysets.

Read: Python Django format date

Limit the selected fields in Union Operation

In this section, you will learn what we mean by limiting the selected fields while performing Union Operation.

In Django, we can’t always perform union operations on querysets. The fact that querysets do not have the same columns and datatypes.

However, it’s possible in some cases that these models have certain common fields. As a result, in this situation, we limit the fields that are picked and then do a union operation. And, to do so we use the Django values_list argument.

Let’s see an example to understand the concept:

Before we start the demonstration, I’ll show you the models and explain how to create them.

Firstly, we create the EmpDetails model.

from django.db import models

# Create your models here.

class EmpDetails(models.Model):
    Name = models.CharField(max_length=200)
    Gender = models.CharField(max_length=20)
    Position = models.CharField(max_length=100)
    Country = models.CharField(max_length=100)
    
    def __str__(self):  
        return "%s %s %s %s" % (self.Name, self.Gender, self.Position, self.Country)  

Next, we create the EmpSalary model.

from django.db import models

# Create your models here.

class EmpSalary(models.Model):
    Name = models.CharField(max_length=200)
    Gender = models.CharField(max_length=20)
    Salary = models.FloatField()
    
    def __str__(self):  
        return "%s %s %s" % (self.Name, self.Gender, self.Salary)
Limit the selected fields in Union Operation Models

After the successful creation of models, register the model in the admin.py file of your Django app ‘myAPP’.

from django.contrib import admin
from .models import EmpDetails
from .models import EmpSalary

# Register your models here.

class AdminEmpDetails(admin.ModelAdmin):
    list_display = ['Name', 'Gender', 'Position', 'Country']

class AdminEmpSalary(admin.ModelAdmin):
    list_display = ['Name', 'Gender', 'Salary']

admin.site.register(EmpDetails, AdminEmpDetails)
admin.site.register(EmpSalary, AdminEmpSalary)
Limit the selected fields in Union Operation Register Models

Now let’s see with an example how to perform the union operation on querysets that are based limited field.

So run the following code in your Python shell.

# Import

from myApp.models.empdetails import EmpDetails
from myApp.models.empsalary import EmpSalary

# QuerySet

queryset1 = EmpDetails.objects.all()
queryset1

queryset2 = EmpSalary.objects.all()
queryset2

# Union Operation

queryset2.union(queryset1)
limit the selected fields in union operation
limit the selected fields in union opertion in django

In the above code

  • firstly we get all the records from the EmpDetails model by using the querysets.
  • Then, we also get all the records from the EmpSalary model by using the querysets.
  • Next, we use the Union Operation to get all records by combining both querysets. But, we get an error.

Now, to resolve this error we can use the values_list parameter of Django to limit the selected fields and after that perform a union operation.

# Import

from myApp.models.empdetails import EmpDetails
from myApp.models.empsalary import EmpSalary

# QuerySet

queryset1 = EmpDetails.objects.values_list("Name", "Gender")
queryset1

queryset2 = EmpSalary.objects.values_list("Name","Gender")
queryset2

# Union Operation

queryset2.union(queryset1)
limit the selected fields in union operation using python django

Conclusion

In this Django Tutorial, we have discussed “Union operation on models Django” and we have also discussed the following topics in this tutorial.

You may also like to read the following Python Django tutorials.