所以我目前正在使用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
答案 0 :(得分:2)
追溯的关键部分是:
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)