1

I want to know if the following query is being optimized by django. I have an address model that is indexed on the field User but not on the field zip_code.

When I do:

Address.objects.get(user=user, zip_code=zip_code)

What I hope happens is that the query first takes advantage of the index to return addresses associated with the user, and then it iterates through the list of addresses for that user and matches the one that has the given zip_code.

However, I'm afraid that this query will not take advantage of the fact that I have the user model indexed on users and will instead iterate through all addresses trying to make sure both the user and zip_code match.

1
  • 3
    it is not Djanog but underline DB will use index Commented Sep 11, 2014 at 17:35

1 Answer 1

1

This question has nothing whatsoever to with Django. Django is not a database, and is not in any way responsible for index optimization. Django simply translates the query to SQL and passes it to the real database. It might be that Postgres does what you describe: to find out, you can use the Django Debug Toolbar to run EXPLAIN on the particular query, and see what indexes are used. However, if this is a query you will do a lot, you probably want to create a combined index on user_id and zip_code anyway.

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

2 Comments

How does this question have nothing to do with Django? I'm essentially asking if Django translates this correctly. I don't see the point in creating a combined index since users should only have 1-10 addresses anyways.
Daniel is correct. Django just builds a SQL statement based on the fields in your model and the filter you specify. Postgres (and databases in general), have complex things called "query optimizers" that take that query string and attempt to figure out the fastest possible way to retrieve the results. And here's the kicker... Postgresql (and any other database) might decide that a sequential table scan is best and not use your finely crafted and clever index. And the Query Optimizer is almost always correct.

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.