我有以下表格:
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 ,但无济于事。
与往常一样,非常感谢任何帮助。