Slide 1

Slide 1 text

Duplicate SQL queries in Django Senko Rašić, Good Code

Slide 2

Slide 2 text

We’re hiring!

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

models.py:! ! class Author(Model): name = CharField(…) ! class Book(Model): author = ForeignKey(Author, …) title = CharField(…) ! views.py:! ! books = Book.objects.all() ! template.html:! ! {% for book in books %} {{ book.title }} {% endfor %}

Slide 5

Slide 5 text

models.py:! ! class Author(Model): name = CharField(…) ! class Book(Model): author = ForeignKey(Author, …) title = CharField(…) ! views.py:! ! books = Book.objects.all() ! template.html:! ! {% for book in books %} {{ book.title }} by {{ book.author.name }} {% endfor %}

Slide 6

Slide 6 text

models.py:! ! class Author(Model): name = CharField(…) ! class Book(Model): author = ForeignKey(Author, …) title = CharField(…) ! views.py:! ! books = Book.objects.all().select_related(‘author’) ! template.html:! ! {% for book in books %} {{ book.title }} by {{ book.author.name }} {% endfor %}

Slide 7

Slide 7 text

Know thy SQL

Slide 8

Slide 8 text

django.test.TestCase.assertNumQueries()

Slide 9

Slide 9 text

Image credit: Stack Exchange

Slide 10

Slide 10 text

[SQL] repeated query (1000x): SELECT “author"."id", “author”.”name” FROM "author" WHERE "author"."id" = ? [SQL] 1007 queries (1000 duplicates), 945 ms SQL time, 24351 ms total request time django-queryinspect

Slide 11

Slide 11 text

SELECT “author”."id", “author”.”name” FROM "author" WHERE "author"."id" = 1 SELECT “author”."id", “author”.”name” FROM "author" WHERE "author"."id" = 2 SELECT “author”."id", “author”.”name” FROM "author" WHERE "author"."id" = 3 ! … ! SELECT “author”."id", “author”.”name” FROM "author" WHERE "author"."id" = ? django-queryinspect

Slide 12

Slide 12 text

X-QueryInspect-Num-SQL-Queries: 1007 X-QueryInspect-Duplicate-SQL-Queries: 1000 X-QueryInspect-Total-SQL-Time: 945 ms X-QueryInspect-Total-Request-Time: 24351 ms django-queryinspect

Slide 13

Slide 13 text

File "/vagrant/api/views.py", line 178, in get return self.serialize(self.object_qs) File "/vagrant/customer/views.py", line 131, in serialize return serialize(objs, include=includes) File "/vagrant/customer/serializers.py", line 258, in serialize_contact lambda obj: [r.name for r in obj.roles.all()]), File "/vagrant/customer/serializers.py", line 258, in lambda obj: [r.name for r in obj.roles.all()]), ! [SQL] repeated query (6x): SELECT "customer_role"."id", "customer_role"."contact_id", "customer_role"."name" FROM "customer_role" WHERE "customer_role"."contact_id" = ? django-queryinspect

Slide 14

Slide 14 text

Copy production DB to staging server

Slide 15

Slide 15 text

No content