Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invalid parameter to prefetch_related()

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,)
like image 387
BubbleTree Avatar asked Aug 04 '17 18:08

BubbleTree


1 Answers

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.

like image 157
Mahmoud Farid Avatar answered Nov 20 '22 05:11

Mahmoud Farid