简体   繁体   中英

“prefetch_related” working on only side of One-Many relationship

I have two models with one-many relationship (Organization hasMany Locations)

class Organizations(models.Model):
    name = models.CharField(max_length=40)

class Location(models.Model):
    name = models.CharField(max_length=50)
    organization = models.ForeignKey(Organizations, to_field="name", db_column="organization_name", related_name='locations')
    class Meta:
        db_table = u'locations'

Now, while trying to pre-fetch locations while retrieving "Organizations" I am getting this error.

Organizations.objects.prefetch_related('locations')

AttributeError: Cannot find 'locations' on Organizations object, 'locations' is an invalid parameter to prefetch_related()

However, if I preload the other way around it works fine.

Location.objects.prefetch_related('organization')

Note: After pre-loading organizations from location model, the previous error does not occur anymore.

I am using Django version: 1.8.6

It seems this error is only present in the django shell. This works fine in the django app itself

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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