In Django doc:
select_related()"follows" foreign-key relationships, selecting additional related-object data when it executes its query.
prefetch_related()does a separate lookup for each relationship, and does the "joining" in Python.
What does it mean by "doing the joining in python"? Can someone illustrate with an example?
My understanding is that for foreign key relationship, use select_related; and for M2M relationship, use prefetch_related. Is this correct?





























Your understanding is mostly correct:
select_related: when the object that you're going to be selecting is a single object, soOneToOneFieldor aForeignKeyprefetch_related: when you're going to get a "set" of things, soManyToManyFields as you stated or reverseForeignKeys.Just to clarify what I mean by reverse
ForeignKeys, here's an example:The difference is that:
select_relateddoes an SQL join and therefore gets the results back as part of the table from the SQL serverprefetch_relatedon the other hand executes another query and therefore reduces the redundant columns in the original object (ModelAin the above example)You may use
prefetch_relatedfor anything that you can useselect_relatedfor.The tradeoffs are that
prefetch_relatedhas to create and send a list of IDs to select back to the server, this can take a while. I'm not sure if there's a nice way of doing this in a transaction, but my understanding is that Django always just sends a list and says SELECT ... WHERE pk IN (...,...,...) basically. In this case if the prefetched data is sparse (let's say U.S. State objects linked to people's addresses) this can be very good, however if it's closer to one-to-one, this can waste a lot of communications. If in doubt, try both and see which performs better.Everything discussed above is basically about the communications with the database. On the Python side however
prefetch_relatedhas the extra benefit that a single object is used to represent each object in the database. Withselect_relatedduplicate objects will be created in Python for each "parent" object. Since objects in Python have a decent bit of memory overhead this can also be a consideration.