5

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?

3
  • do you've bounded the select_related through the depth arg or a field name? Commented Jan 16, 2013 at 23:14
  • No bounds on it, would that help? Commented Jan 17, 2013 at 2:27
  • Maybe your breakdown isn't just for the null=True; Commented Jan 17, 2013 at 15:43

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is a nice solution. I'll give it a try.
0

From the official document, that is the limitation of the select_related() method, here is the details.

But you could have specified the related field in select_relate(), something like

modelA.objects.select_related('ModelAForeignKeyName__RelatedModelFeildName')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.