【发布时间】:2011-02-14 19:02:15
【问题描述】:
这里是 Django/Python 菜鸟!
这是我的模型:
class Match(models.Model):
date = models.DateTimeField()
court = models.ForeignKey(Court)
players = models.ManyToManyField(User, through='Participant')
class Participant(models.Model):
match = models.ForeignKey(Match)
userid = models.ForeignKey(User)
games_won = models.IntegerField()
class Court(models.Model):
location_name = models.CharField(max_length=100)
number = models.IntegerField()
我目前的看法是:
def index(request):
matches_list = Participant.objects.all()
return render_to_response('squash/base_matches.html', {'matches_list': matches_list}, context_instance = RequestContext(request))
return HttpResponse(output)
我在数据库中的数据如下所示:
[match_id] [date] [userid] [games_won] [court_location_name] [court_number]
1 01-01-2011 mike 6 Queen 5
1 01-01-2011 chris 4 Queen 5
2 01-02-2011 bob 3 Queen 6
2 01-02-2011 joe 4 Queen 6
3 01-03-2011 jessie 5 Queen 2
3 01-03-2011 john 5 Queen 2
我想做的是:
[match_id] [date] [player1] [player2] [p1wins] [p2wins] [game_winner] [court_location_name] [court_number]
1 01-01-2011 mike chris 6 4 mike Queen 5
2 01-02-2011 bob joe 3 4 joe Queen 6
3 01-03-2011 jessie john 5 5 draw Queen 2
这意味着我需要按 match_id 分组。我尝试在我的模板中执行以下操作,但它只聚合了 match_id、日期和时间。我需要能够格式化其余的数据。在前面提到的表格结构中。
{% regroup matches_list by match as matches_group %}
<ul>
{% for event in matches_group %}
<li>{{ event.grouper }}
<ul>
{% for item in blah.list %}
<li>{{ item.date }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
这里有什么建议吗?
更新:我用matches_list = Participant.objects.values('match').annotate(total=Count('match')) 进行了测试,我相信这就是让我聚合的原因。但是我不知道如何在模板中提取正确的字段。例如:
{% for matches in matches_list %}
<p>{{ matches.match.id }}</p>
{% endfor %}
这给了我 3 个条目(我可以看到 3 个
的),但没有打印出来。不知道我需要为{{ matches.match.id }}做什么
【问题讨论】:
-
如何阻止有超过 2 个人的 match_id?如何确定谁是player1,谁是player2?
-
我还没有任何内置控件来执行此操作,因此输入这些控件的管理员只需要知道输入两个人即可。 player1和player2的顺序无关紧要,只需要第一个玩家,然后是第二个玩家。
标签: python django django-orm