追溯外键

时间:2013-02-11 01:46:01

标签: python django

我有以下表格:

class Person (models.Model):

    GENDER_CHOICES = (
                      ('M', 'Male'),
                      ('F', 'Female'),
                      )

    first_name = models.CharField(max_length=50)
    last_name  = models.CharField(max_length=50)
    gender = models.CharField(max_length = 1, choices=GENDER_CHOICES, default='M')
    age = models.IntegerField()
    photo = models.ImageField(upload_to='uploads/images/runners', blank=True)

    def __unicode__(self):
        return '%s, %s' % (self.last_name, self.first_name)

class Runner (models.Model):
    ''' Represents a runner actually in a particular Race '''
    position = models.IntegerField()
    person = models.ForeignKey(Person, related_name="person")
    race = models.ForeignKey(Race)

class Race (models.Model):
    '''An instance of an Event. i.e., the race that is happening this year'''
    year = models.IntegerField()
    description = models.TextField()
    event = models.ForeignKey(Event)

    def leaderboard(self):
        '''
        Orders the leaders and returns the entire set
        Args:
        Returns: 
            A list of Runners ordered by position
        '''
        #board = Runner.objects.prefetch_related("person").filter(race=self).order_by('position') 
        board = Runner.objects.prefetch_related("person")
        print "DEBUG: %s" % board.values()
        return board

我想要完成的是检索并随后编码一个JSON响应,该响应包含一个Runner实例列表,其中包含其中包含的每个相应Person实例的属性。

在排行榜方法中,我编写了一个查询示例。执行后,我得到以下内容:

DEBUG: [{'person_id': 1, 'position': 1, 'id': 1, 'race_id': 1}, {'person_id': 2, 'position': 2, 'id': 2, 'race_id': 1}]

我想要的是让QuerySet使用Person实例和该实例的所有相关属性扩展(并替换)每个'person_id“字段。(即first_name,last_name等。

这可能吗?我尝试过使用prefetch_related()和select_related,但无济于事。

与往常一样,非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

您可以通过以下方式获得比赛中的所有参赛者:

self.runner_set.select_related('person')

这将包含所有参赛者,并且人员表格会有JOIN

当您使用.values()时,它会返回外键值,这不是您想要的。

如果需要,可以使用外键中的related_name="runners"进行竞赛。然后,您就可以通过self.runners...

访问它了