我创建了一些自定义管理员验证,就像我想要的一样,除了在一种情况下。
它旨在检查以确保在多对多字段中创建的列表具有正确数量的项目(“玩家”),并且列表中的男女比例是可以接受的。
def clean(self):
super(GameRosterForm, self).clean()
players = self.cleaned_data.get('players', None)
RosterRulesOn = self.cleaned_data.get('RosterRulesOn', None)
women = players.filter(sex='F')
womenPct = int((women.count()/float(players.count()))*100)
if RosterRulesOn is True and players.count() < 8:
raise ValidationError('Rosters must have at least 8 players. You have only selected %s.' % (players.count()))
if RosterRulesOn is True and players.count() > 18:
raise ValidationError('Rosters cannot have more than 18 players. You have selected %s.' % (players.count()))
if RosterRulesOn is True and womenPct < 40:
raise ValidationError('Women must make up at least 40 percent of roster. They only constitute %s percent now.' % (womenPct))
return self.cleaned_data
正如我所说,它在大多数情况下都可以正常工作,但是当用户尚未将播放器添加到 m2m 时,它会返回错误:'list' object has no attribute 'filter' with reference to the women=players.filter(性别='F') 行。
我尝试了一些“if”和“try”条件来尝试绕过问题,但找不到有效的解决方案。