Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django slow query when ForeignKey null=True

I set null=True on one of the ForeignKey fields in my Django model, and now when I query that model, it is about 10 times slower. (I'm using select_related())

Looking at my Postgres logs before and after the change gives clues to the reason:

  • Before setting null=True, the SQL that is generated is a single select statement with a couple of inner joins.
  • After setting null=True, the SQL that is generated leaves out one of the joins and instead is followed by thousands of identical select statements.

So it's the classic n+1 query issue, and until this is fixed, how can I set null=True on a ForeignKey field without taking performance hits?

like image 595
Gady Avatar asked Nov 12 '22 13:11

Gady


1 Answers

You can solve this through a raw query. Take a look to the query that is generated before putting null=True and execute it via a raw query instead of using 'top-level django ORM'. The breakdown is due the ORM don't the Postgres server, so you can avoid useless code generation running the SQL code directly.

like image 77
trinchet Avatar answered Nov 15 '22 07:11

trinchet