Different ways of making queries to Django Database

Introduction

After creating models and migrating them to the database, we make queries to the database to get meaningful information from it. A query is a request for data or information from a database table or group of tables. It is important to make queries to the database as it allows us to get access to accurate information about our data, create and retrieve data, update existing data, filter a group of data, and get and delete data we don't find useful anymore.
In Django, data are retrieved from the database by constructing a Queryset on the model's Manager which is objects by default and added to every Django Model's class. A Queryset is a representation or collection of objects in the database which can be narrowed down to retrieve specific subsets by using different methods.

Some of the popular methods used to make queries are:

get: This is used to retrieve a particular entity from the database.

Example

Assuming I have a model that stores the data for a Product

from django.db import models
from django.utils import timezone

class Product(models.Model):
     name = models.CharField(max_length=150)
     amount = models.DecimalField(max_digits=200, decimal_places=2)
     created_at = models.DateTimeField(default=timezone.now)

After storing a series of products in the database, I can retrieve a specific product by using the get method.

Product.objects.get(name="book")

create: The create method is used to store a new entity in the database.

Example To store a new product in my Product database:

new = Product.objects.create(name="biro", amount=20)
new.save()

The save method saves the new product I created, without calling the method, the database isn't hit and the object isn't saved.

filter: This method returns a new queryset that matches the lookup parameters. To get the list of products that their amount is 100:

Product.objects.filter(amount=100)

exclude: This method returns a new queryset that doesn't match the lookup parameters. It is the opposite of filter.

update: it is used to update the existing objects in the database.

Conclusion

There are other queries used in Django like count, exists, list, annotate etc. Most can be found in Django documentation.

Did you find this article valuable?

Support Ubaydah's Blog🎉 by becoming a sponsor. Any amount is appreciated!