Opened 23 months ago

Last modified 2 months ago

#21422 assigned Cleanup/optimization

prefetch_related does not document restriction

Reported by: pab@… Owned by: donaldharvey
Component: Documentation Version: master
Severity: Normal Keywords:
Cc: loic@… Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


I have just been trying to track down a performance issue in my application using Django 1.6. The solution was to use prefetch_related(), bit it didn't quite work as expected. The documentation was great as far as it went and so I found the necessary function with little fuss - well done! However it didn't warn me that prefetch_related() must be restricted to a homogenous set of results.

In particular, I had query that needed to fetch data for objects found through a GenericForeignKey and then a ManyToManyField. While the pre-fetch claimed it had worked, it only actually queried the ManyToManyField results for the first matching ContentType of the GenericForeignKey. Looking at the code, this is a deliberate design decision, but it is not documented anywhere I could see.

I understand why this restriction is in place and so am not asking for a feature enhancement. Instead, I think the documentation for this function needs to make clear that pre-fetching objects referenced by GenericForeignKeys is only supported if the query has restricted the key to one ContentType.

Change History (3)

comment:1 Changed 23 months ago by loic84

  • Cc loic@… added
  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Triage Stage changed from Unreviewed to Accepted

I can confirm that the implementation relies on the assumption that all the retrieved objects are homogenous.

This limitation should be documented.

comment:2 Changed 3 months ago by ubernostrum

  • Easy pickings set

comment:3 Changed 2 months ago by donaldharvey

  • Easy pickings unset
  • Owner changed from nobody to donaldharvey
  • Status changed from new to assigned
  • Version changed from 1.6 to master
Note: See TracTickets for help on using tickets.
Back to Top