尝试通过For循环显示数据库中每个用户的总amount_won

时间:2012-01-20 03:07:16

标签: python mysql django

我正在尝试为数据库中的每个user_name显示amount_won的总和。我的数据库是:

赌注表

id
player_id
stakes
amount_won
last_play_date

玩家表

id
user_name
real_name
site_played

models.py

class Player(models.Model):
    user_name = models.CharField(max_length=200)
    real_name = models.CharField(max_length=200)
    SITE_CHOICES = (
        ('FTP', 'Full Tilt Poker'),
        ('Stars', 'Pokerstars'),
        ('UB', 'Ultimate Bet'),
    )
    site_played = models.CharField(max_length=5, choices=SITE_CHOICES)
    def __unicode__(self):
        return self.user_name
    def was_created_today(self):
        return self.pub_date.date() == datetime.date.today()

class Stakes(models.Model):
    player = models.ForeignKey(Player)
    stakes = models.CharField(max_length=200)
    amount_won = models.DecimalField(max_digits=12, decimal_places=2)
    last_play_date = models.DateTimeField('Date Last Updated')
    def __unicode__(self):
        return self.stakes

class PlayerForm(ModelForm):
    class Meta:
        model = Player

class StakesForm(ModelForm):
    class Meta:
        model = Stakes

Views.py

def index(request):
    latest_player_list = Player.objects.all().order_by('id')[:20]
    total_amount_won = Stakes.objects.filter(player__user_name='test_username').aggregate(Sum('amount_won'))
    return render_to_response('stakeme/index.html', {
        'latest_player_list':     latest_player_list, 
        'total_amount_won': total_amount_won
     })

和index.html

<h1> Players </h1>

{% if latest_player_list %}
<ul>
{% for player in latest_player_list %}
    <li><a href="/stakeme/{{ player.id }}/">{{ player.user_name }} </a><br>Total Won: {{ total_amount_won }}
</li>
{% endfor %}
</ul>
<br>
{% else %}
<p>No players are available.</p>
{% endif %}

<h3><a href="/stakeme/new/">New Player</a></h3>

如果我将views.py部分保留为(player__user_name='test_username'),它将显示金额赢取:如下Total Won: {'amount_won__sum': Decimal('4225.00')}使用test_username的amount_won(4225.00)作为每个用户名。理想情况下,我希望它显示Amount Won:对于for循环中的每个用户名,仅显示为“Amount Won:4225.00”。

我开始明白这是我的想法,但我已经阅读了有关聚合和注释之间差异的文档,我无法理解它。我认为我的数据库没有正确设置为此使用注释,但我显然可能是错的。

1 个答案:

答案 0 :(得分:2)

退房:https://docs.djangoproject.com/en/dev/topics/db/aggregation/

players = Player.objects.annotate(total_amount_won=Sum('stakes__amount_won'))

players[0].total_amount_won # This will return the 'total amount won' for the 0th player

因此,您可以将players传递给模板并循环遍历它。

修改

你的views.py看起来像是:

def index(request):
    players = Player.objects.annotate(total_amount_won=Sum('stakes__amount_won'))
    return render_to_response('stakeme/index.html', {'players': players,})

模板看起来像:

<h1> Players </h1>
{% if players %}
<ul>
{% for player in players %}
<li>
    <a href="/stakeme/{{ player.id }}/">{{ player.user_name }} </a><br>Total Won: {{ player.total_amount_won }}
</li>
{% endfor %}
</ul>    
<br />
{% else %}
<p>No players are available.</p>
{% endif %}
<h3><a href="/stakeme/new/">New Player</a></h3>