Retrieving related fields

Apologies in advance: this should be (and probably is) trivially simple, but I haven’t found the answer in the ‘models’ documentation.

Two models, one contains a foreign key to two. I want to retrieve a collection containing the whole of one, with each returned instance including a field from the related instance in two. In SQL, a simple equi-join from one to two and include two.field in the SELECT list. I want this to be done in one database ‘hit’.

What’s the syntax for this? And what have I either missed or misunderstood in the documentation?

Many thanks in advance for your answer (and your patience).

Hello @SimonSellickSRA :wave:

You are looking for select_related so in your case something like

Book.objects.select_related("author")

Which results in

SELECT
   book.*,
   author.*
FROM book
INNER JOIN author ON (book.author_id = author.id)
1 Like