我尝试使用PersonScore在这3张桌子上进行内部联接但却无法找到人物类型。我做错了什么?
模型:
class PersonScore(models.Model):
id = models.IntegerField(primary_key=True) # AutoField?
person = models.ForeignKey(‘Person’)
class Person(models.Model):
id = models.IntegerField(primary_key=True) # AutoField?
name = models.CharField(max_length=255)
class PersonType(models.Model):
person = models.ForeignKey(‘Person’)
type = models.CharField(max_length=255)
代码:
PersonScore.objects.filter(person__name="Bob").prefetch_related("person__persontype")
错误:
Cannot find 'persontype' on Person object, 'person__persontype' is an invalid parameter to prefetch_related()
代码:
PersonScore.objects.filter(person__name="Bob").prefetch_related("person__persontype_set")
错误:
KeyError: (1L,)
答案 0 :(得分:3)
在PersonScore中,你应该使用select_related而不是prefetch_related
PersonScore.objects.filter(person__name="Bob").select_related("person__persontype")
如果你想使用prefetch_related,你将使用它与Person
Person.objects.filter(personscore_set__name="Bob").prefetch_related("personscore_set"
您可以在此处查看更多详细信息:What's the difference between select_related and prefetch_related in Django ORM?
我希望这会对你有所帮助。