我正在尝试将字符串转换为int,这样我就可以保持一个正在运行的total,并希望能够在django模板中输出。
def stats(request):
stats = []
players = Player.objects.all()
for player in players:
player_stats = PlayerStat.objects.filter(player__id=player.pk)
for n,stat in enumerate(player_stats):
if n == 0:
passing_completions = stat.passing_completions
else:
passing_completions += stat.passing_completions
stats.append((player.first_name, player.last_name, player.team, passing_completions))
return render_to_response('preps/stats.html', {'stats': stats, })
我试过在stat.passing_completions周围添加int(),但这只会抛出错误invalid literal for int() with base 10: ''
。
因此,我使用isdigit()
方法来确保只有带数字的字符串尝试进行如下转换:
for player in players:
player_stats = PlayerStat.objects.filter(player__id=player.pk)
for n,stat in enumerate(player_stats):
if n == 0:
if stat.passing_completions.isdigit():
passing_completions = int(stat.passing_completions)
else:
if stat.passing_completions.isdigit():
passing_completions += int(stat.passing_completions)
stats.append((player.first_name, player.last_name, player.team, passing_completions))
但是我得到了Caught TypeError while rendering: 'int' object is not iterable
的错误
模型结构
class PlayerStat(models.Model):
player = models.ForeignKey(Player)
week_num = models.CharField(
max_length = 10,
choices = (('1', 'Sep 2nd',), ('2', 'Sep 9th',), ('3', 'Sep 16th',),('4', 'Sep 23rd',), ('5', 'Sep 30th',), ('6', 'Nov 2nd',),('7', 'Nov 7th',), ('8', 'Nov 14th',), ('9', 'Nov 21st',),('10', 'Nov 28th',), ('11', 'Dec 4th',), ('12', 'Dec 11th',), ),
blank = True,
null=True
)
rushing_attempts = models.CharField(
max_length = 100,
verbose_name = "Rushing Attempts",
blank=True
)
rushing_yards = models.CharField(
max_length = 100,
verbose_name = "Rushing Yards",
blank=True
)
rushing_touchdowns = models.CharField(
max_length = 100,
verbose_name = "Rushing Touchdowns",
blank=True
)
passing_completions = models.CharField(
max_length = 100,
verbose_name = "Passing Completions",
blank=True
)
passing_attempts = models.CharField(
max_length = 100,
verbose_name = "Passing Attempts",
blank=True
)
passing_yards = models.CharField(
max_length = 100,
verbose_name = "Passing Yards",
blank=True
)
passing_touchdowns = models.CharField(
max_length = 100,
verbose_name = "Passing Touchdowns",
blank=True
)
receptions = models.CharField(
max_length = 100,
verbose_name = "Receptions",
blank=True
)
receiving_yards = models.CharField(
max_length = 100,
verbose_name = "Receiving Yards",
blank=True
)
receiving_touchdowns = models.CharField(
max_length = 100,
verbose_name = "Receiving Touchdowns",
blank=True
)
任何帮助都将不胜感激。
谢谢
我知道这是一个老问题,但是如果有人需要,这里有一个小的解决方案,我可以毫无问题地将字符串转换为int:
就这样。;)
您应该检查
stat.passing_completions
是否为空字符串。您可以使用:我有时会用这个愚蠢的伎俩:
在字符串前面加一个零可以保证字符串中至少有“0”。 现在,可以肯定的是,您可以用正则表达式从“'0'+someString”中提取所有数字。
相关问题 更多 >
编程相关推荐