How to prefetch a @property with a Django queryset?
prefetch_related
and select_related
are instructions that are compiled into the database query/ies. Passing it the name of a pure Python property doesn't work because your database cannot know about them. You would have to select/prefetch the database fields/relations that the property uses under the hood:
qs = Place.objects.select_related('placebestpic')
Now, calling the property will not hit the db:
for p in qs: # do stuff with p.bestpicurl
Even though you are following a reverse relation here, you do not use prefetch_related
. From the select_related
docs:
You can also refer to the reverse direction of a OneToOneField in the list of fields passed to select_related — that is, you can traverse a OneToOneField back to the object on which the field is defined. Instead of specifying the field name, use the related_name for the field on the related object.