What are Django QuerySet and to execute one ? (Part X)

In this tutorial, we are going to learn what are Django ORM and QuerySet, and how to perform one in our Django Blog web application.

This tutorial is a part of our series on Creating Blog Website using Django.

Link to the Previous tutorial:

Introduction to HTML and creating your First Template(Part IX)

What is Django QuerySet

You might remember, Model in Django is a special kind of object which can be saved in the database. It provides a framework for creating a more similar type of objects.

For more information, on Django models check :

Creating Django Models and their Tables in the database

Therefore, now a QuerySet can be defined as a list containing all those objects we have created using the Django model. Further, we can perform multiple operations on the QuerySet to add, delete, modify or retrieve objects already saved in the database.

Initializing Django Shell

To work with QuerySets, we need to run the commands in the interactive Django shell. For that, open up your terminal and run the command.

python manage.py shell

Queryset for viewing all the objects

If you are regularly following this series, you may remember that we have created a model Post in blog1/models.py file.

Let us view all the objects saved using that framework. For that, we first need to import the model Post from the database. To do that, run the command :

>>> from blog1.models import Post

Then, perform the query to view all the objects :

>>> Post.objects.all()

OUTPUT :

<QuerySet []>

The command will provide with all the Post objects in a list-like format.

(Your output may vary depending on the Post you have created in your Application.)

Queryset for creating new objects :

Remember, the last time we have created the Post using the Django SuperUser interface. Turns out, we can also create a post from the Django Interactive Shell.

For that, we first need to import the Users registered on our Application and select the one creating this Post. Run the command :

>>> from django.contrib.auth.models import User

Then, run the next command to view all the users :

>>> User.objects.all()

OUTPUT :

<QuerySet [<User: aayush-05>]>

(Your’s might vary.)

Now, let us create an instance of the author to access it easily for the upcoming commands :

>>> User1 = User.objects.get(username='aayush-05')

Then, finally create the new object for model Post using the command :

>>> Post.objects.create(author=User1, title='Title1', text='First Post')

Want to see if it worked, run the previously mentioned command :

>>> Post.objects.all()

OUTPUT :

<QuerySet [<Post: Title1>]>

Ta-da ! Here, it is.

Next part of this Django tutorial:

We will continue with some more queries in the upcoming post.

Drop your queries in the comment section below

Also, have a look at :

 

Leave a Reply

Your email address will not be published. Required fields are marked *