1

I can't figure out how the default Django ORM processes queries like:

Model.objects.filter(foreign__field=value)

Does it make a lookup on each row, or is it smart enough to resolve the foreign field id(s) with the target value?

Or is it cheaper to make it this way?

value_temp = Foreign.objects.get(field=value)
Model.objects.filter(foreign=value_temp)

1 Answer 1

2

Since the Django ORM is just a front-end to SQL, and since SQL performance will be very database- and context-dependent, it's hard to generalize. I would say that, in general, unless you have a very good understanding of the performance tradeoffs involved you shouldn't bother trying to work around the straightforward approach. Both Django and the SQL databases take pains to optimize typical query patterns.

In the specific example you cited, the first call will do a JOIN between the two tables, while the second will make two separate queries, each of a single table. So the factors include: the round-trip time to access the database; whether there's an index on the foreign key; whether there's an index on field; and the specific values that are in the database. My guess is that the first will almost always be faster, since databases are tailored for just this kind of lookup. (You ask: Does it make a lookup on each row or is it smart enough to resolve the foreign field id with the target value? The answer is that it's the database, not Django, that makes that decision; and, yes, the database will generally take the most efficient route.)

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

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.