So, I just wanted to share a few straightforward tips about database access optimization. For the most those tips are
not something you should go to your code base and start refactoring. Actually for existing code it’s a better idea to
profile first (with Django Debug Toolbar for example). But those tips are very easy to start applying, so keep them
in mind when writing new code!
Accessing Foreign Key Values
If you only need the ID of the Foreign Key:
Do
Don't
If you have a foreign key named author, Django will automatically store the primary key in the property
author_id, while in the author property will be stored a lazy database reference. So if you access the id via
the author instance, like this post.author.id, it will cause an additional query.
Bulk Insert on Many to Many Fields
Do
Don't
Counting QuerySets
If you only need the count:
Do
Don't
Empty QuerySets
If you only need to know if the queryset is empty:
Do
Don't
Reduce Query Counts
Do
Don't
Select Only What You Need
Let’s say the Invoice model has 50 fields and you want to create a view to display just a summary, with the
number, date and value: