Kindle Notes & Highlights
Read between
March 20 - March 27, 2021
For quick and easy profiling needs, django-debug-toolbar is quite handy. We can also use Python profiling tools, such as the hotshot module for detailed analysis. In Django, you can use one of the several profiling middleware snippets to display the output of hotshot in the browser. A recent live-profiling solution is django-silk. It stores all the requests and responses in the configured database, allowing aggregated analysis over an entire user session,
the documentation suggests, you should enable the cached template loader in production. This avoids the overhead of reparsing and recompiling the templates each time it needs to be rendered.
Reduce database hits with select_related: If you are using a OneToOneField or a Foreign key
Reduce database hits with prefetch_related: For accessing a ManyToManyField method or, a Foreign key
Fetch only needed fields with values or values_list:
Denormalize models:
Add an index:
Create, update, and delete multiple rows at once: Multiple objects can be operated upon in a single database query with the bulk_create(), update(), and delete() methods. However, they come with several important caveats such as skipping the save()
By default, Django stores its user session in the database. This usually gets retrieved for every request. To improve performance, the session data can be stored in memory by changing the SESSION_ENGINE setting.
For basic caching strategies, it might be easier to use a caching framework. Among the popular ones are django-cache-machine and django-cachalot. They can handle common scenarios, such as automatically caching results of queries to avoid database hits every time you perform a read.
Another common caching pattern is to cache forever. Even after the content changes, the user might get served stale data from the cache. However, an asynchronous job, such as a Celery job, also gets triggered to update the cache. You can also periodically warm the cache at a certain interval to refresh the content.
Don't treat caching as integral to the working of your site. The site must fall back to a slower but working state even if the caching system breaks down.
Every time you revisit the code, use the opportunity to take a step back and find a cleaner design, identify a hidden pattern, or think of a better implementation. Other developers, and perhaps your future self, will thank you for it.
__str__() method is called for string representation of your models rather than the awkward sounding __unicode__() method. This is one of the most evident ways of identifying Python 3 ported code:
In Python 3, all exceptions must be derived (directly or indirectly) from BaseException. In practice, you will create your custom exceptions by deriving from the Exception class. As a major improvement in error reporting, if an exception occurs while handling an exception, the entire chain of exceptions is reported: