In Django, we can easily create our database tables by defining some model classes. Here, we define different types of model fields also known as attributes. Within this framework, we have Django Queryset that we can use to access the attributes of different models.
In Django QuerySet, we have different types of model queries that we can use for accessing data of all models, specific model, or specific objects of each model. I’m going to explain all these different types of Django queries in brief.
Django Queries – Different QuerySet Explained
Before we’re going to explore different types of queries in Django, Let me first show you some models.py code. In this models.py code, I’ve defined some model objects that we’ll query in this article…
from django.db import models
class Customer(models.Model):
name = models.CharField(max_length=100, null=True)
phone = models.CharField(max_length=100, null=True)
email = models.EmailField(null=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.name
class Product(models.Model):
CATEGORY = (
('Indoor', 'Indoor'),
('Outdoor', 'Outdoor')
)
name = models.CharField(max_length=100)
price = models.FloatField(null=True)
category = models.CharField(max_length=100, choices=CATEGORY)
description = models.TextField(max_length=200, null=True)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
class Order(models.Model):
STATUS = (
('Pending', 'Pending'),
('Out For Delivery', 'Out For Delivery'),
('Delieverd', 'Delieverd')
)
customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL)
product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL)
created = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=100, choices=STATUS)
Let me explain you this above models.py code, what I did here. I’ve created 3 different models – Customer, Product, Orders…
So, I’ve added 4 different attributes in this Customer model – name, phone, email, and date_created. In Product model, I’ve added 5 different attributes – name, price, category, description, and created field.
In Order Model, we have connected customer and product attribute by using Foreign Key. Which means Order objects of individual customer will be linked to only that Customer object. Same as product field will be connected with the object of product model with the help of foreign key. There are different types of Django queries that we can use to access all objects of models or all attributes of a specific object within a model by the help of id.
Accessing All Objects of Specific Model in Django
Now let start with accessing all objects of a specific model. Here, we’re going to extract the attributes of all objects within a Customer Model. we know that each object will be consist of 4 different attributes – name, email, phone, date_created. In customer model, I have already created 4 different objects “PK Karn, Sohail, Mahure, Ritesh”. If I want to access all attributes of these 4 objects then django query will be:
customers = Customer.objects.all()
In the above Customer.objects.all() – our Customer is a model and all() function is used to access all objects within the Customer model. Then we’ve stored these data within our customers variable. Because we have different objects here, therefore, our data has stored within the list. To access these data in our templates, we have to iterate “customers” variable in “for loop“.
{% for customer in customers %}
<p>{{customer.name}}</p>
<p>{{customer.phone}}</p>
<p>{{customer.email}}</p>
<p>{{customer.date_created}}</p>
{% endfor %}
Now It will loop all data of all different objects one by one.
Accessing Specific Object Of Model(by using get method):
Accessing all objects of a model can be easy with .all() method. But what if you just want to access data of specific object within a model. In such case, you can use get() method to access a specific object. Here, I want to access only “PK Karn” objects of Customer model. So, here we will use get() method.
But To access specific object with get(), you need to pass at least one attribute within get() function e.g get(name=”PK Karn”). But there is a problem, what if two different objects will have same name?, In such case, it will throw an error. So, instead of using any attribute, we use “id” attribute. Because id attribute of object will be always unique. this “id” attribute will be created automatically, whenever you will create any new object.
customer = Customer.objects.get(id=1)
Here, you don’t need to use for loop. Because our customer variable contains only information related about one object. You can access this data within your template e.g:
<p>{{customer.name}}</p>
<p>{{customer.phone}}</p>
<p>{{customer.email}}</p>
<p>{{customer.date_created}}</p>
Accessing Objects By using Django filter Query
You can also access all objects of a model with certain conditions or filters. Django has filter() function to access objects within a model with some conditions. Here, I’m going to access objects of Product model, But I only want to access objects with “Indoor” categories. Here, we can use .filter() method to do this.
products = Product.objects.filter(category="Indoor")
Because here we’re not accessing any single object. We’re accessing Product objects with filter of Indoor Category. Therefore, .filter() function has returned set consist of different objects. To access these data within the templates, you need to use for loop.
{% for product in products %}
<p>{{product.name}}</p>
<p>{{product.price}}</p>
<p>{{product.category}}</p>
<p>{{product.description}}</p>
{% endfor %}
Other Important Django Queries in QuerySet
There are some other important Django queries that I’m going to explain you in short.
1. To Access first Or Last Object of Model
firstCustomer = Customer.objects.first() Or lastCustomer = Customer.objects.last()
2. To Return Or Access all objects related to Particular Foreign Model Object
Suppose you want to access all objects of Order model but only related to specific Customer. Here you can use
customer = Customer.objects.get(id=1) (PK Karn) Object. Now following query is used to access all Order of (PK karn)Customer Object.
pkorder = customer.order_set.all()
3. Queries to Sorting Objects in Ascending Or Descending
ascending = Product.objects.all().order_by('id')
or
descending = Product.objects.all().order_by('-id')
You need to use order_by(‘attributes’) following .all() method to sorting.
Read Also: Create Restful API’s with Django rest framework – Serializers, CRUD
These were some main Django queries that you can use to access objects or data out of our Models or Django database. I hope you will like this.
Please don’t forget to bookmark our blog, If you want such kind of articles. Because we always post such kind of programming related article on this blog.
Thank’s to read…