6

I'm trying to convert a string into an int so that I can keep a running total and would like to be able to output in the django template.

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, })

I've tried adding int() around stat.passing_completions but then that just throws the error invalid literal for int() with base 10: ''.

So then I used the isdigit() method to make sure only strings with digits were trying to be converted like this:

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))

but then I get the error of Caught TypeError while rendering: 'int' object is not iterable

model Structure

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
        )

Any help would be appreciated.

Thanks

bigmike7801
  • 3,908
  • 9
  • 49
  • 77
  • It's a numerical football statistic that I'm trying to get a running total of and would like to be able to output in the django template. – bigmike7801 Sep 16 '11 at 18:00
  • I've tried adding int() around stat.passing_completions? Why? If `stat.passing_completions` is a string, why is it defined that way? And if you get `invalid literal for int() with base 10: ''.` that does not mean throw around random code. That means look at your data to see why the column is empty. Why is the column (a) not a number and (b) empty? – S.Lott Sep 16 '11 at 18:01
  • I was throwing around random code. Sometimes the string is empty so that's why I was checking to make sure it was a digit. The person who created the DB defined the column as a varchar and not an int I believe. – bigmike7801 Sep 16 '11 at 18:06
  • "The person who created the DB defined the column as a varchar and not an int I believe."? This is not a question of belief. It's really a question of fact. Can you find the model definition? If so, can you include the model definition in the question? – S.Lott Sep 16 '11 at 18:10
  • [IntegerField](https://docs.djangoproject.com/en/1.3/ref/models/fields/#integerfield) and [DecimalField](https://docs.djangoproject.com/en/1.3/ref/models/fields/#decimalfield) are really the things to be using. – j_syk Sep 16 '11 at 18:32

3 Answers3

12

I sometimes use this stupid trick :

 a = int('0' + someString)

Adding a zero in front of a string guaranties me to have at least "0" in the string. Now, to be sure, you may extract all the digits from the "'0'+someString" with a regular expression.

Louis
  • 2,854
  • 2
  • 19
  • 24
4

I know this is an old question, but if someone needs, here is a small solution I use to convert strings to int without problems:

def int_or_0(value):
    try:
        return int(value)
    except:
        return 0

Just it. ;)

Jayme Tosi Neto
  • 1,189
  • 2
  • 19
  • 41
2

You should check if stat.passing_completions is not an empty string. You could use:

for player in players:
    player_stats = PlayerStat.objects.filter(player__id=player.pk)
    for n,stat in enumerate(player_stats):
        if n == 0 and stat.passing_completions:  # n is 0 and passing_completions is something meaningful
                passing_completions = int(stat.passing_completions)
        elif stat_passing_completions:  # n is not 0
            passing_completions += int(stat.passing_completions)
        else:
            pass  # in this case, stat.passing_completions is an empty string ('')

    stats.append((player.first_name, player.last_name, player.team, passing_completions))
sinan
  • 6,809
  • 6
  • 38
  • 67
  • I still get the error of `Caught TypeError while rendering: 'int' object is not iterable` :( – bigmike7801 Sep 16 '11 at 18:11
  • @bigmike: That's because `passing_completions` is not a number. It's a list or a tuple of some kind. Please **update** the question to include the initialization value for `passing_completions` so we can see **all** the code. – S.Lott Sep 16 '11 at 18:15
  • @bs0d1: I'm a noob to python and your answer taught me a couple tricks. Thank you for that. – bigmike7801 Sep 16 '11 at 18:40