注释未显示/正常工作

时间:2012-01-24 19:12:38

标签: python django django-templates django-views

我问了这个question有关注释的问题,找到了前5名受伤最严重的球员,但现在我遇到了显示正确信息的问题,我认为这应该是它自己的问题。

这是我目前的观点:

def home(request):
    context={}
    most_recent = PlayerInjury.objects.all().order_by('-timestamp')[:5]
    news = News.objects.all()
    most_injured = PlayerInjury.objects.annotate(injury_count=Count('id')).order_by('-injury_count')[:5]
    print most_injured
    context['most_injured'] = most_injured
    context['most_recent'] = most_recent
    context['news'] =  news
    return render_to_response('dash/home.html', RequestContext(request, context))

models.py

class PlayerInjury(models.Model):
    player =  models.ForeignKey(Player)
    injury_type = models.ForeignKey(Injury)
    injury_date = models.DateField(verbose_name='Injured On', null=True, blank=True)
    description = models.CharField(verbose_name='Description', max_length=180, null=True, blank=True)
    status = models.ForeignKey(Status)
    projected_return = models.DateField(verbose_name='Projected Return Date', null=True, blank=True)
    hide = models.BooleanField(default=False)
    returned = models.BooleanField(default=False)
    timestamp = models.DateTimeField(auto_now_add=True)

class Player(models.Model):
    first_name = models.CharField(verbose_name='First Name', max_length=30, null=True, blank=True)
    last_name = models.CharField(verbose_name='Last Name', max_length=30, null=True, blank=True)
    team = models.ForeignKey(Team, related_name='Team played for')
    pob = models.CharField(verbose_name='Place of Birth', max_length=100, null=True, blank=True)
    dob = models.DateField()
    age =  models.IntegerField(null=True, blank=True)
    height = models.CharField(verbose_name='Height', max_length=10, null=True, blank=True)
    weight = models.CharField(verbose_name='Weight', max_length=10, null=True, blank=True)
    drafted_by = models.ForeignKey(Team, related_name='drafted by')

然而,当我打印出most_injured时,我得到了:
  - 球员A
  - 球员B
  - 玩家A

当真的,我认为应该显示如下:
  - 球员A
  - 玩家B

由于玩家A受到的伤害超过玩家B

有什么建议吗?

我认为这是应该如何运作的   - 球员A(2伤害)
  - 球员B(1伤)
  - 等等

2 个答案:

答案 0 :(得分:1)

尝试这样做:

most_injured = Player.objects.annotate(injury_count=Count('playerinjury')).order_by('-injury_count')[:5]

答案 1 :(得分:1)

您正在查询单个PlayerInjury个对象,因此您的结果中当然有多个玩家。

如果您Count id,则每个ID只有1个对象,因此您将始终获得一个计数。

如果你想要受伤的球员对象,你需要

Player.objects.annotate(count=Count('playerinjury')).order_by('-count')