[Django]-Unable to understand a line from the django tutorial

6👍

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

order_by('pub_date') means order by ASC ascending.
So order_by('-pub_date') means order by DESC descending.

[:5] mean get first 5 records.

So

Then output ', '.join([q.question_text for q in latest_question_list])
so output will become something like question1, question2, question3, question 4, question 5

Remember their note there There’s a problem here, though: the page’s design is hard-coded in the view. If you want to change the way the page looks, you’ll have to edit this Python code. So let’s use Django’s template system to separate the design from Python by creating a template that the view can use.

5👍

Because it’s convenient, let’s use Django’s own database API, which we covered in Tutorial 2. Here’s one stab at a new index() view, which displays the latest 5 poll questions in the system, separated by commas, according to publication date

with emphasis on

which displays the latest 5 poll questions in the system, separated by commas, according to publication date.

latest_question_list = Question.objects.order_by('-pub_date')[:5]

will return the last 5 questions that were added to the database while. Getting the first 5 would have been [5:].

You should read [Explain Python’s slice notation to get more knowledge on how it works.

Remember the results of the first query is assigned to latest_question_list ? Now you need a way to display the results

This part output = ', '.join([q.question_text for q in latest_question_list])

Read this post on Python Join to get more understanding of how python join works. It basically takes the values in a list and concatenates them using the seperator(in this case a comma).

The last part [q.question_text for q in latest_question_list] is called a LIST COMPREHENSION

1👍

All it does it to take 5 records from Question table ordered by publication date and make a string separated by commas of question_text column of all those records.

Leave a comment