If your model has multiple foreign keys you can:
- Call
.select_related()
, that will “follow” all non-null foreign-key relationships
- Call
.select_related('foreign_key1', 'foreign_key2', ...)
, that will “follow” only the foreign-key provided as arguments.
Note that "to follow a FK relationship" means selecting additional related-object data when the query is executed (by performing a SQL join). This will make the main query heavier but can be used to avoid N + 1 queries problem.
According to select_related
documentation, the first method (without arguments) is not recommended as "it is likely to make the underlying query more complex, and return more data, than is actually needed."
If your model has "nested" foreign keys with other models (i.e. Book <>-- Author <>-- Hometown
) you can also use select_related
as follow:
- Call
Book.select_related('author__hometown')
, that will “follow” the author's foreign-key (in Book model) and the hometown's foreign-key (in Author model).
If your model has many-to-many or many-to-one relations you would like to retrieve from the database, you should take a look at prefetch_related.
user
andarticle
are both ForeignKey fields onComment
. The above is the equivalent ofComment.objects.select_related('user', 'article').all()
. (Context: I'm researching whether you canselect_related()
across multiple relationships. The above does not do that.) – Izanami