这是我的代码。
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}}
但它没有显示任何内容,
我能做什么,
感谢
答案 0 :(得分:27)
查看http://docs.djangoproject.com/en/dev/topics/db/queries/#limiting-querysets
不支持负索引(即
Entry.objects.all()[-1]
)。
尝试:
first_element = Location.objects.all()[0]
last_element = Location.objects.all().reverse()[0]
- 更新8/6/17 -
基于@MisterRios的评论,
从1.6开始,Django支持在查询集上使用.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 :(得分:3)
您可能无法对查询集进行否定索引,但您可以将该查询集放入列表中,然后将其索引。
locations = list(Location.objects.all())
first_element = locations[0]
last_element = locations[-1]
但这种效率非常低,并且只应在表中存在少量位置时使用,并且您希望保持代码简单。否则,如果确实需要提高效率,请参阅@ pterk的答案,涉及聚合和Min / Max。
答案 2 :(得分:3)
要获取最后一个[-1]
,请尝试Location.objects.latest('id')
,如文档中所示:
https://docs.djangoproject.com/en/1.3/ref/models/querysets/#latest
答案 3 :(得分:1)
最后: - Location.objects.reverse()[0]
或强>
Location.objects.all()[Location.objects.count()-1] // BAD WAY
首先: Location.objects.all()[0]
注意:不支持负索引。所以,Location.objects.all()[-1]
会给你一个
AssertionError
答案 4 :(得分:1)
如果有人来这里获取相关模型的第一个和最后一个项目 - 有效地做到这一点的唯一方法是将相关字段转换为列表或使用count()来获取最后一个项目的索引(使用Django 1.11.2 ):
class Parent(models.Model):
name = models.CharField(max_length=200)
class Child(models.Model):
parent = models.ForeignKey(Parent, on_delete=models.CASCADE, related_name='children')
name = models.CharField(max_length=200)
class ParentTest(TestCase):
def test_parent(self):
# create some data
for p in range(10):
parent = Parent.objects.create(name=p)
for c in range(10):
parent.children.create(name=c)
with self.assertRaises(AssertionError): # can't negative index
parents = Parent.objects.prefetch_related('children')
for parent in parents:
first = parent.children.all()[0]
last = parent.children.all()[-1]
with self.assertNumQueries(22): # 2 for prefetch and 20 for access
parents = Parent.objects.prefetch_related('children')
for parent in parents:
first = parent.children.first()
last = parent.children.last()
with self.assertNumQueries(22): # 2 for prefetch and 20 for access
parents = list(Parent.objects.prefetch_related('children'))
for parent in parents:
first = parent.children.first()
last = parent.children.last()
with self.assertNumQueries(12): # 2 for prefetch and 10 for last
parents = Parent.objects.prefetch_related('children')
for parent in parents:
first = parent.children.all()[0]
last = parent.children.reverse()[0]
with self.assertRaises(AssertionError): # can't negative index
parents = list(Parent.objects.prefetch_related('children'))
for parent in parents:
first = parent.children.all()[0]
last = parent.children.all()[-1]
with self.assertNumQueries(2): # 2 for prefetch
parents = Parent.objects.prefetch_related('children')
for parent in parents:
children = list(parent.children.all())
first = children[0]
last = children[-1]
with self.assertNumQueries(2):
parents = Parent.objects.prefetch_related('children')
for parent in parents:
first = parent.children.all()[0]
last = parent.children.all()[parent.children.count() - 1]
答案 5 :(得分:1)
效率可能很低
obj_list=Location.objects.all()
first_element=obj_list[0]
last_element=obj_list[len(obj_list)-1]
答案 6 :(得分:0)
如果您有办法对位置对象进行排序,请查看聚合(最小和最大)。 http://docs.djangoproject.com/en/dev/topics/db/aggregation/
您可能会在id
上尝试Min和Max,但请尽量避免这种情况,因为ID的顺序不是保证(至少不会跨越各种数据库引擎)
答案 7 :(得分:0)
obj_list
是 QuerySet 的一个实例,QuerySet 有 own methods:
obj_list.latest('pk')
obj_list.earliest('pk')
obj_list.first()
obj_list.last()
答案 8 :(得分:0)
and
ERROR 2021-05-17 02:14:20,744 log 30 139680490260288 Internal Server Error: /camp/
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/opt/project/apps/web/views.py", line 419, in camp
amount_by_daily = draw_amount_by_daily()
File "/opt/project/apps/web/charts.py", line 16, in draw_amount_by_daily
daily_list = DailyReport.objects.filter(category="daily_all").order_by('create_at').values("create_at")[-12:]
File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 288, in __getitem__
"Negative indexing is not supported."
AssertionError: Negative indexing is not supported.
daily_list = DailyReport.objects.filter(category="daily_all").order_by('create_at').values("create_at")[-12:]
daily_list = DailyReport.objects.filter(category="daily_all").order_by('-create_at').values("create_at")[:12]
result = list(reversed(daily_list))