In this Python Django Tutorial, we will understand Union operation on models Django. And we will also discuss examples related to the Union operation on models. Here is the list of topics that we are going to cover.
- Union operation on models Django
- Union Operation on same model using Django
- Union Operation on different models using Django
- Limit the selected fields in Union Operation
Union operation on models Django
In this section, we learn what Union Operation means. 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, we will discuss one of the Set Operations, called Union Operation.
To combine the results of two or more querysets, we use the Union Operator. By default, the Union operator picks only separate values or we can say distinct values. If you want to allow duplicate values, use the all=True parameter.
The Union Operation can be applied on the same or different models. And, 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 same model using Django
I hope you have a clear understanding of what Union Operation is. Let’s now turn our attention to the practical implementation of union operations.
In this section, we will learn how to use Union Operation on the same model. And to better understand the concept, we’ll look at some examples.
Before we start the demonstration, I’ll show you the model and explain how to create it.
Firstly, we have to create the model in the model.py file of the app.
Code to Create Model:
from django.db import models
# Create your models here.
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)
- Firstly, we will create an Employee database using the Django model.
- Then add respective data feilds such as First_Name, Last_Name, Position, Age to the model.
Next, register the Employee model by writing the below code in the admin.py file.
Code to Register Model:
from django.contrib import admin
from .models import Employee
# Register your models here.
class AdminEmployee(admin.ModelAdmin):
list_display = ['First_Name', 'Last_Name', 'Position', 'Age']
admin.site.register(Employee, AdminEmployee)
Now, we will run the query on that database to perform Union Operation.
Example #1
In this example, we will perform Union Operation on the same model.
# Import
from DjangoFilter.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)
- In this example, we get the record on the basis of the filters such as Age greater than 28 and First_Name is Maria by using the querysets.
Example #2
Here we are going to perform Union Operation on Model Fileds Position and Last_Name.
# Import
from DjangoFilter.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)
- In this example, we get the record on the basis of the filters such as Position is Vice President and Last_Name is Johnson by using the querysets.
- Next, we use the Union Operation to combine the records in both querysets.
- Here, we will only get the distinct common values in both querysets.
So, if we want to get the duplicate values also, use the all=True parameter with union operation.
# Union Operation
queryset1.union(queryset2, all=True)
Then, the output will be:
Read: Python Django vs ReactJS
Union Operation on different models using Django
In this section, we will learn how to use Union Operation on the different models. And to better understand the concept, we’ll look at some examples.
Before we start the demonstration, I’ll show you the models and explain how to create them.
Firstly, we create a Customer model.
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)
- Here we create Customer database using Django models with respective data fields Customer_Name, Customer_Contact_Name, Customer_Country, and 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)
- Here we create Supplier database using Django models with respective data fields Supplier_Name, Supplier_Contact_Name, Supplier_Country, and Supplier_City.
After the successful creation of models, we register them.
from django.contrib import admin
from .models.customer import Customer
from .models.supplier import Supplier
# Register your models here.
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)
Now, we will run the queries on that databases to perform Union Operation.
Example #1
In this example, we will perform Union Operation on the different models.
# 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)
- In this example, firstly we get the record from Customer model on the basis of the filter Customer_Country=’UK’ by using the querysets.
- Then, we get the record from Supplier model on the basic of the filter Supplier_Country=’UK’ by using the querysets.
- Next, we use the Union Operation to get the record by combining both the querysets.
Example #2
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)
- In this example, firstly we get the record from Customer model on the basis of the filter primary key values by using the querysets.
- Then, we also get the record from Supplier model on the basic 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, we’ll learn what do 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)
- Here we create EmpDetails database using Django models with respective data fields Name, Gender, Position, and 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)
- Here we create EmpSalary database using Django models with respective data fields Name, Gender, and Country.
After the successful creation of models, we register them.
from django.contrib import admin
from .models.empdetails import EmpDetails
from .models.empsalary 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)
Now, we will run the queries on that databases to perform Union Operation.
Example #1
In this example, we are going to perform union operations on the above-created models.
# 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)
- In this example, firstly we get all the record from EmpDetails model by using the querysets.
- Then, we also get all the record from EmpSalary model by using the querysets.
- Next, we use the Union Operation to get the all record by combining both querysets. But, we get an error.
The output is as below:
Now, to resolve this error we can use the values_list parameter of Django to limit the selected fields then do union.
# 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)
You may also like to read the following Python Django tutorials.
- Python Change Django Version
- Python Django vs Pyramid
- If statement in Django template
- Get URL parameters in Django
- Encrypt and decrypt password in Django
- Django CRUD example with PostgreSQL
- How to encrypt and decrypt password in Django
In this Django Tutorial, we have discussed “Union operation on models Django” and we have also discussed the following topics in this tutorial.
- Union operation on models Django
- Union Operation on same model using Django
- Union Operation on different models using Django
- Limit the selected fields in Union Operation
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.