2011-07-08 84 views
0

我有以下型號:Django的 - 查詢集多維列表

class Fixture(models.Model): 
    id = models.AutoField(primary_key=True) 
    home_team = models.ForeignKey(Player, related_name="home") 
    away_team = models.ForeignKey(Player, related_name="away") 
    game_week = models.PositiveSmallIntegerField(max_length=2, default=0) 

我想要做的就是創建一個多維列表組由「game_week」屬性我所有的固定對象。例如:

fixtures[0] = [<FixtureObject 1>, <FixtureObject 2>] 
    fixtures[1] = [<FixtureObject 3>, <FixtureObject 4>] 
    fixtures[2] = [<FixtureObject 5>] 
    fixtures[3] = [<FixtureObject 6>] 

其中fixture列表索引是不同的遊戲周。什麼是最簡單,最pythonic的方式來做到這一點?

做到這一點是使用字典

回答

2

最簡單的方法:

fixtures = Fixture.objects.all() 
fixture_dict = {} 
for fixture in fixtures: 
    fixture_dict.setdefault(fixture.game_week, []).append(fixture)