我有以下内容:
def foo(self):
print "Test"
scores = BasicScore.objects.filter(event__id=self.id).order_by('score_date')[0:1]
print scores
#return s
#return Score.objects.all().order_by('start_date')[:1]
return scores
在我的模板中:
event.foo.0.value
这会很好用,我将能够使用 BasicScore 类。
但是之前我有: 返回分数[0]
但是我在日志中得到了这个:
Test
[]
异常(exception)情况:
Exception Type: IndexError
Exception Value:
list index out of range
Exception Location: /Library/Python/2.7/site-packages/django/db/models/query.py in __getitem__, line 207
Python Executable: /usr/bin/python
我对 Django/Python 有点陌生,但为什么 one 的列表会成功返回,但访问 [0] 最终会出错,访问一个空集?
最佳答案
列表 []
不是一个列表,它是一个零列表,scores[0]
应该引发一个 IndexError
。
关于python - Django 模型过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11388283/