试图通过for循环显示数据库中每个用户的总赢得金额

2021-09-27 05:18:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图显示数据库中每个用户名的金额总和。我的数据库是:

桩表

id
player_id
stakes
amount_won
last_play_date

播放器表

id
user_name
real_name
site_played

你知道吗型号.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

你知道吗视图.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
     })

以及索引.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>

如果我离开视图.py分区为(player__user_name='test_username')它将显示赢得的金额:如下Total Won: {'amount_won__sum': Decimal('4225.00')}为每个用户名使用测试用户名的赢得金额(4225.00)。理想情况下,我希望它显示amountwon:for for循环中的每个用户名,并仅显示为“amountwon:4225.00”。你知道吗

我开始意识到这一点,但我已经阅读了有关聚合和注释之间的差异的文档,我无法理解它。我认为我的数据库设置不正确,无法使用annotate,但我显然可能是错的。你知道吗