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

问题描述:

这是我的代码。如何获取第一个元素和最后一个元素使用django,Location.objects.all()

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

如果负面索引是问题,first_element应该至少显示一些内容,您在什么程度上调试了这个? – gladysbixly 2011-03-05 10:11:21

+0

如果您找到了解决方案,请更新并关闭此问题。 – zsquare 2012-05-04 18:49:30

看一看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] 

- 更新17年8月6日 -

基于@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

+0

从1.6开始,Django支持在查询集上使用'.first()'和'.last()':last_element = Location.objects.first()' 'last_element = Location.objects.last()' See: https://docs.djangoproject.com/zh/dev/ref/models/querysets/#django.db.models.query.QuerySet.first – MisterRios 2017-04-12 12:19:03

+0

谢谢!更新答案。 – zsquare 2017-06-08 06:22:20

如果您有排序位置对象的方法,请查看聚合(最小值和最大值)。 http://docs.djangoproject.com/en/dev/topics/db/aggregation/

你也许会做的MIN和MAX id但要尽量避免为ID的顺序不是保证(至少不能进行的跨各种数据库引擎)

你可能不能够负索引查询集,但可以将该查询集放入列表中,然后将其索引。

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

这是可怕的,虽然效率不高,如果有在你的表位置少数,才应使用,并且要保持代码的简洁。否则,如果真的需要这样做,请参阅@ pterk的答案,涉及聚集和Min/Max。

最后: - Location.objects.reverse()[0]

OR

  Location.objects.all()[Location.objects.count()-1] // BAD WAY 

第一:Location.objects.all()[0]

注:不支持负索引。所以,Location.objects.all()[-1]将抛出你的 Asse田

+2

-1用于误导人 - .all()[1]是* second *元素,而不是第一个。 – 2011-03-05 11:31:59

+0

@Tomasz,感谢您的纠正....我的错误:( – Tauquir 2011-03-05 21:09:29

得到最后一个[-1]尝试Location.objects.latest('id')所看到的文档:

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

+0

这个答案似乎仍然有效,第一个答案没有。 – 2016-02-16 08:37:34

如果任何人来到这里获得的第一个和最后一个项目相关模型 - 有效地做到这一点的唯一方法是将相关字段转换为列表或使用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]