Introduction
This is another article where the main focus is just to be able to join several query results from several operations to get data from objects. Actually, there are several QuerySet result variable exist. The aim is to be able to present a single variable consisting of all those QuerySet result variable. That variable will be easy for further print operation in the Django view template later on. The following is the sample of the source code :
from django.shortcuts import render from django import template from django.contrib.auth.decorators import login_required from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from django.urls import reverse from .models import Unit @login_required(login_url="/login/") def home(request): marketing_unit = Unit.objects.filter(id=55) planning_unit = Unit.objects.filter(id=56) production_unit = Unit.objects.filter(id__gte=551).filter(id__lte=554) distribution_unit = Unit.objects.filter(id__gte=561).filter(id__lte=564) all_unit = [] all_unit.append(marketing_unit) all_unit.append(planning_unit) all_unit.append(production_unit) all_unit.append(distribution_unit)
Solution
The solution is actually very simple. Just change the operation for combining all the QuerySet result by retrieving it from the object class. Instead of using a list and append it one by one, just use the following way. It is by using a certain operator sign to join and combine all of them. The following is the modification from the above source code :
-
Just execute the script for retrieving a single QuerySet result like normal. It is just like in the above script execution. For an example ‘Unit.objects.filter(id=55)
-
Save every QuerySet result into a variable. For an example in the above script execution there are marketing_unit, planning_unit, production_unit, distribution_unit
-
Finally, instead of using the list variable and append all of the QuerySet result variable, just use the ‘|’ (pipe) operator to join or to combine all of them.So, the pattern will be ‘all_unit = marketing_unit | planning_unit | production_unit | distribution_unit’
So, overall, the final modification of the above source code will exist as follows :
from django.shortcuts import render from django import template from django.contrib.auth.decorators import login_required from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from django.urls import reverse from .models import Unit @login_required(login_url="/login/") def home(request): marketing_unit = Unit.objects.filter(id=55) planning_unit = Unit.objects.filter(id=56) production_unit = Unit.objects.filter(id__gte=551).filter(id__lte=554) distribution_unit = Unit.objects.filter(id__gte=561).filter(id__lte=564) all_unit = marketing_unit | planning_unit | production_unit | distribution_unit