Sanwar lal
Sanwar lal

Reputation: 15

What does order_by() do in Django?

Documentation says order_by() returns a new QuerySet.

When I print Question.objects.order_by('-pub_date') where Question is class name in models.py, it prints queryset object.

I am confused whether order_by() returns a new Queryset or executes a query?

What is happening internally during execution in Django in below code?

from django.http import HttpResponse
from .models import Question

def index(request): 
   latest_question_list = Question.objects.order_by('-pub_date')[:5]
   output = ', '.join([q.question_text for q in latest_question_list])
   return HttpResponse(output)

Also please explain line 5 in above code?

Upvotes: -1

Views: 118

Answers (2)

Chukwujiobi Canon
Chukwujiobi Canon

Reputation: 4091

What does order_by() do in Django?

It produces a database query such that results returned by the QuerySet of the said query are ordered by the given field ordering. So that you can order results by ascending or descending field order. This query is then executed at the database and the database performs the ordering.

I am confused whether order_by() returns a new QuerySet or executes a query?

It does both. It returns a new QuerySet and the QuerySet is evaluated when you perform one of the actions outlined at When QuerySets are evaluated [djangoproject.com] on the QuerySet.

What is happening internally during execution in Django in below code?

from django.http import HttpResponse
from .models import Question

def index(request):
   # Make a QuerySet whose result will be ordered by pub_date in descending order. A reference to this QuerySet is stored in the variable latest_question_list
   latest_question_list = Question.objects.order_by('-pub_date')[:5]

   # Evaluate this QuerySet by iterating over it in the List Comprehension [python.org]
   output = ', '.join([q.question_text for q in latest_question_list])

   return HttpResponse(output)

Upvotes: 0

Sayse
Sayse

Reputation: 43320

Django queries are lazily executed so it doesn't perform the query until you attempt to get the results, hence why it says it returns a query set. You attempt to get the results when you iterate over them for the list comprehension in line 5..

Line 5 is just a list comprehension used within a joining string operation

Upvotes: 0

Related Questions