提问人:Melonendk 提问时间:11/2/2017 更新时间:11/2/2017 访问量:961
Django model.objects.all() 在正常调用时给出了超出范围的列表索引
Django model.objects.all() gives list index out of range upon calling it normally
问:
所以我目前正在使用 Django 处理一个私人项目,当我尝试为团队加载页面时,它只是说“列出范围之外的索引”,然后我使用 object.all() 从模型团队中获取每个团队,
在模板中,我使用 for 循环将每个团队发布到我一直在尝试使用 order_by() 和 first() 的页面上,但它们似乎都没有帮助。
我的回溯在这里 http://dpaste.com/2S4Q7FY
我在这里做错了什么,我应该改变什么
景观
def teams(request):
teams = Team.objects.all()
context = {
'teams': teams,
}
if request.user.is_authenticated():
logged_in_user = get_object_or_404(User, pk=request.user.pk)
context['logged_in_user'] = logged_in_user
return render(request, 'teams.html', context)
模型团队
class Team(models.Model):
name = models.CharField(max_length=16)
logo = models.ImageField(upload_to='teams/avatars', default='static/img/userpreload.png')
background = models.ImageField(upload_to='teams/backgrounds', default='static/img/userpreload.png')
description = models.TextField(blank=True)
people_needed = models.PositiveSmallIntegerField()
members = models.ManyToManyField(User, through='TeamMembership')
accepts_applications = models.BooleanField()
@property
def teamleaders_listable(self):
leaders = self.members.filter(teammembership__leader=True)
string = leaders[0].extendeduser.nickname
for leader in leaders[1:]:
string += ", " + leader.extendeduser.nickname
return string
@property
def multiple_teamleaders(self):
if len(self.members.filter(teammembership__leader=True)) > 1:
return True
else:
return False
def __str__(self):
return self.name
答:
2赞
Alasdair
11/2/2017
#1
回溯的关键部分是:
File "/home/melonendk/webapps/victory_genki_dk/victory/staff/models.py" in teamleaders_listable
22. string = leaders[0].extendeduser.nickname
File "/home/melonendk/webapps/victory_genki_dk/lib/python3.6/Django-1.11.6-py3.6.egg/django/db/models/query.py" in __getitem__
289. return list(qs)[0]
Exception Type: IndexError at /teams/
Exception Value: list index out of range
这告诉您失败是因为查询集为空。leaders[0]
self.members.filter(teammembership__leader=True)
您可以稍微更改代码以使用,而不是遍历查询集。当查询集为空时,这将返回空字符串。", ".join()
''
@property
def teamleaders_listable(self):
leaders = self.members.filter(teammembership__leader=True)
return ", ".join(l.extendeduser.nickname for l in leaders)
评论
0赞
Melonendk
11/2/2017
非常感谢你们,你们基本上是我今天的英雄:D
评论
leaders
leaders[0]
len(self.members.filter(teammembership__leader=True))
.count()
SELECT COUNT(*)
self.members.filter(teammembership__leader=True).count() > 1
qs.exists()
qs.count() > 0
> 1