如何使用Django,Location.objects.all()获取第一个元素和最后一个元素

2024-06-17 11:23:48 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码。

obj_list=Location.objects.all()
first_element=obj_list[0]
last_element=obj_list[-1]

那么

return render_to_response(template_name, {
        'first_element':first_element,
        'last_element':last_element,
    })

在模板中:

{{ first_element.terminal_id}} {{last_element.terminal_id}}

但什么也没有

我能做什么

谢谢


Tags: toidobj密码returnobjectsresponselocation
3条回答

您可能无法对queryset进行负索引,但可以将该queryset放入列表中,然后进行索引。

locations = list(Location.objects.all())
first_element = locations[0]
last_element = locations[-1]

不过,这是非常低效的,只有在表中有少量位置并且希望代码保持简单的情况下才应该使用。否则,如果确实需要提高效率,请参阅@pterk的答案,包括聚合和最小/最大值

看看http://docs.djangoproject.com/en/dev/topics/db/queries/#limiting-querysets

Negative indexing (i.e. Entry.objects.all()[-1]) is not supported.

尝试:

first_element = Location.objects.all()[0]
last_element = Location.objects.all().reverse()[0]

--更新8/6/17--

根据@MisterRios的评论

从1.6开始,Django支持在querysets上使用.first().last() first_element = Location.objects.first() last_element = Location.objects.last()

参考:https://docs.djangoproject.com/en/1.7/ref/models/querysets/#django.db.models.query.QuerySet.first

要获取最后一个[-1]请尝试Location.objects.latest('id'),如文档中所示:

https://docs.djangoproject.com/en/1.3/ref/models/querysets/#latest

相关问题 更多 >