Optimization

SQL statement execution

  • Iteration

  • Slicing

    • Basically no

    • Only when using step

      • [3:10:2]

  • repr

  • len

  • bool

Query improvement

installation

Prerequisites

settings.py

Setting up URLconf

urls.py in the root directory

Enabling middleware

settings.py

Configuring Internal IPs

settings.py

1. Output comment count - Using annotate()

N+1 problem

Before improvement (11 times)

Query Count Before

After improvement (1 time)

Query Count After

2. Output post author name - Using select_related()

select_related fetches data through SQL JOIN

In 1:1, 1:N relationships with reference relationship (N -> 1, where foreignkey is defined)

Before improvement (11 times)

Select Related Before

After improvement (1 time)

Select Related After

3. Output comments for each post - Using prefetch_related()

prefetch_related fetches data through Python join

In M:N, 1:N relationships with reverse reference relationship (1->N)

Before improvement (11 times)

Prefetch Related Before

After improvement (2 times)

Prefetch Related After

4. Output author name and comments for each post

Before improvement (111 times)

Complex Query Before

After improvement (2 times)

Complex Query After

SQL Join

SQL Join Diagram

ex)

+

Setting profile photo using Gravatar

https://en.gravatar.com/site/implement/arrow-up-right

Method 1) @property setting

accounts > models.py

Method 2) Create templatetags

accounts > templatetags > gravatar.py

  • Must create __init__.py inside templatetags directory!

Templates

templates > _nav.html

Last updated