Following a foreign key relationship incurs a DB lookup, as with this example from documentation:
# Hits the database. e = Entry.objects.get(id=5) # Hits the database again to get the related Blog object. b = e.blog
As outlined in the
select_related documentation, you can optimize this query to also fetch the Blog in a single SQL query if you know you’re going to need it.
What I’m interested in understanding is the number of DB lookups my application performs on foreign keys where following a foreign key relationship requires that extra SQL query at time of access. I’ve found printing out
len(connection.queries) super helpful for understanding how many queries a particular block of code makes, but I’m also interested in narrowing in on those queries which could benefit from a
It would be great to know that a particular web request followed foreign key relationships in a way which didn’t hit the cache
n times, somehow. Is there any way to hook into that?