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:
null=True
, the SQL that is generated is a single select statement with a couple of inner joins.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=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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With