In fact, it is equivalent to querying the database twice. For friends with high efficiency requirements, it may not meet your requirements. Is there any good solution?
The answer is just today.Django select_related ()
Let's take the above example.
B = book. Objects. select_related (). Get (ID = 4)
P = B. name # No database query
C = P. Age # No database query
And:
B = book. Objects. Get (ID = 4) # No select_related () in this example.
P = B. name # query the database.
C = P. Age # query the database.
You can also control the depth of the query cache.
B = book. Objects. select_related (depth = 1). Get (ID = 4)
P = B. name # No database query
C = P. Age # query the database.
in the preceding example, you should understand the role of Django select_related (). I think Django select_related () is a bit like a cache structure,
query the records of Foreign keys and put them in the record set. The database does not need to be queried the next time you use data, get data directly from the cache record set.
however, everything has two sides. As mentioned above, it is advantageous. I may say that it is not good. I feel that since it caches records, it may be inappropriate for applications with high timeliness
and data cannot be updated in a timely manner, some of Django's mechanisms work well, for example: [ Django template syntax ], [ Django template extends ], [ Django template filter ]