简体   繁体   English

追溯外键

[英]Tracing back foreign-keys

I have the following tables: 我有以下表格:

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)

and

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)

and

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

What I am trying to accomplish is to retrieve and subsequently encode a JSON response that contains a list of Runner instances with the attributes of each corresponding Person instance contained therein. 我要完成的工作是检索并随后编码一个JSON响应,其中包含一个Runner实例列表,其中包含每个对应的Person实例的属性。

In the leaderboard method, I have written an example of my Query. 在排行榜方法中,我编写了一个查询示例。 Upon executing it, I get the following: 执行后,我得到以下信息:

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

What I want that to look like is to have the QuerySet expand (and replace) each 'person_id" field with a Person instance and all the associated attributes of that instance. (ie, first_name, last_name, etc. 我想要的样子是让QuerySet用Person实例以及该实例的所有关联属性(即first_name,last_name等)扩展(并替换)每个“ person_id”字段。

Is this possible? 这可能吗? I've tried playing around with both prefetch_related() and select_related but to no avail. 我试过玩prefetch_related()和select_related,但无济于事。

As always, any help is much appreciated. 与往常一样,我们非常感谢您的帮助。

You can get all of the runners in a race by doing: 您可以通过以下方法使所有跑步者参加比赛:

self.runner_set.select_related('person')

This will contain all of the runners, and will have a JOIN to the person table. 这将包含所有跑步者,并将对个人表具有JOIN

When you use .values() , then it gives you back the foreign key values, which is not what you want. 当您使用.values() ,它将返回您不需要的外键值。

If you want, you can use the related_name="runners" within your foreign key to Race. 如果需要,您可以在Race的外键中使用related_name="runners" Then you'll be able to access it via self.runners... 然后,您将可以通过self.runners...访问它self.runners...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM