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?
You can solve this through a raw query. Take a look to the query that is generated before putting
null=Trueand execute it via arawquery 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.