I'm trying to do an inner join on these 3 tables using PersonScore but it can't find persontype. What am i doing wrong?
models:
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)
code:
PersonScore.objects.filter(person__name="Bob").prefetch_related("person__persontype")
error:
Cannot find 'persontype' on Person object, 'person__persontype' is an invalid parameter to prefetch_related()
code:
PersonScore.objects.filter(person__name="Bob").prefetch_related("person__persontype_set")
error:
KeyError: (1L,)
In the PersonScore you should to use select_related instead of prefetch_related
PersonScore.objects.filter(person__name="Bob").select_related("person__persontype")
if you want to use prefetch_related, you will use it with Person
Person.objects.filter(personscore_set__name="Bob").prefetch_related("personscore_set"
you can check more details here: What's the difference between select_related and prefetch_related in Django ORM?
I hope that will be helpful for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With