3 django
我正在编写官方 Django 教程,网址为https://docs.djangoproject.com/en/1.10/intro/tutorial03/。我无法理解这一行。有人可以帮我分解一下吗?
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)
Run Code Online (Sandbox Code Playgroud)
编辑:用户说这不是一行代码。代码的格式化方式让人不清楚,因为它们使用大字体并且经常将单行分解为多行。这是它在网站上的格式:
Question.objects.order_by('-pub_date')[:5]
output = ', '.join([q.question_text for q
in latest_question_list])
Run Code Online (Sandbox Code Playgroud)
输出行是缩进的,这让我相信它是同一行的一部分,但由于某种原因 Stack Overflow 不允许我这样做。
latest_question_list = Question.objects.order_by('-pub_date')[:5]\noutput = ', '.join([q.question_text for q in latest_question_list])\nreturn HttpResponse(output)\nRun Code Online (Sandbox Code Playgroud)\n\norder_by('pub_date')表示按ASC升序排序。\n所以order_by('-pub_date')表示按顺序排序DESC降序排列。
[:5]表示获取前 5 条记录。
所以
\n\n然后输出', '.join([q.question_text for q in latest_question_list])\nso 输出将变成类似question1, question2, question3, question 4, question 5
记住他们的笔记There\xe2\x80\x99s a problem here, though: the page\xe2\x80\x99s design is hard-coded in the view. If you want to change the way the page looks, you\xe2\x80\x99ll have to edit this Python code. So let\xe2\x80\x99s use Django\xe2\x80\x99s template system to separate the design from Python by creating a template that the view can use.
\n\n\n因为\xe2\x80\x99s方便,让\xe2\x80\x99s使用Django\xe2\x80\x99s自己的数据库API,我们在教程2中介绍过。这里\xe2\x80\x99s在一个新索引上进行了一次尝试( ) 视图,显示系统中最新的 5 个投票问题,以逗号分隔,按发布日期排列
\n
强调
\n\n\n\n\n根据发布日期显示系统中最新的 5 个投票问题,以逗号分隔。
\n
latest_question_list = Question.objects.order_by(\'-pub_date\')[:5]\nRun Code Online (Sandbox Code Playgroud)\n\n将返回添加到数据库的最后 5 个问题。获得前 5 名本来就是[5:]。
您应该阅读[解释 Python 的切片表示法,以获取有关其工作原理的更多知识。
\n\n还记得第一个查询的结果被分配给 吗latest_question_list?现在您需要一种显示结果的方法
这部分output = \', \'.join([q.question_text for q in latest_question_list])
阅读这篇关于Python Join的文章,进一步了解 python join 的工作原理。它基本上获取列表中的值并使用分隔符(在本例中为逗号)将它们连接起来。
\n\n最后一部分[q.question_text for q in latest_question_list]称为列表理解
| 归档时间: |
|
| 查看次数: |
2444 次 |
| 最近记录: |