Filter and order objects along with publishing them using QuerySet in Django(Part XI)

In this tutorial, we are going to understand a few more intricacies of QuerySet in Django, some more of their features like filtering and ordering (based on different conditions) and also learn to publish the Post Objects on the main Blog application.

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

For an introduction to the QuerySet, check out the below-mentioned post :

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




Filtering objects in Django

To work with QuerySets, run the interactive Django Shell using the command :

python manage.py shell

The big reason of using QuerySet in the first place, is its ability to filter out objects based on the conditions provided, something not possible with Django SuperUser interface.

To perform this, we use the obviously named query “filter” along with the condition to be applied in the parenthesis such as “title=Post1”.

Have a look at implementing the filer function :

>>> Post.objects.filter(author=User1)

Let us take the case as we want to view all the published post. But for that we first have to import the timezone module :

>>> from django.utils import timezone

Now, run the below command :

>>> Post.objects.filter(published_date__lte=timezone.now())

OUTPUT :

<QuerySet []>

Ordering objects in Django

One great feature of QuerySet is that it allows you to view the list of objects in some specific order as you want.

For sorting the objects in the way they are created; run the command :

>>> Post.objects.order_by('published_date')

OUTPUT :

<QuerySet [<Post: Title1>, <Post: Title2>]>

To further view the list in the descending order, just add a ‘-‘ sign in front of “published_date” :

>>> Post.objects.order_by('-published_date')

OUTPUT :

<QuerySet [<Post: Title2>, <Post: Title1>]>

Publishing Posts through QuerySet in Django

Till now, we have published Posts through the graphical user-based admin control section that Django provides by default. Now, we will learn how to do the same but with the Django interactive shell.

First, as we have previously done; create an instance of post to be published by running the command :

>>> newpost = Post.objects.get(title="Title3")

After that, publish the with the usual publish() function.

>>> newpost.publish()

 

There ends the interaction with the QuerySets. Check out more of these functions in the Django documentation.

Next part of this Django tutorial series:

Feel free to drop any problems in the comments section below.

Also, have a look at other posts

What is Exponential Search in Python and how to implement it

What is new in Python 3 as compared to Python 2?


Leave a Reply

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