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?
select_relatedthrough thedeptharg or a field name?null=True;