I started reviewing the performed SQL queries so I can improve them (caching, reformulating them, etc) in my Django project.
For example, to get a single object from the database, this:
Company.objects.filter(pk=1)[:1]
Is faster than:
Company.objects.filter(pk=1)
Because in the former we are limiting the number of lookups. This is obvious, but what is not too obvious is how to set a limit when accessing a property of a model that happens to be a ForeignKey. For example, if CompanyModel
is a model that has a OneToOneField
to Company, and we try to access some property from the main model:
test = Company.objects.filter(pk=1)[:1]
profile = test.CompanyProfile.owner
The query that will be executed to get information about the CompanyProfile will not have any kind of limit, thus will traverse the whole table to find as many records as possible. How can I set a limit so that it does not do that?