Reputation: 11523
First. I am not sure how to write this question so it would be more useful to SO users, maybe someone could edit the question.
So, I have these two models:
class A(models.Model):
...
class B(models.Model):
foreign = models.Foreignkey(A)
aproperty = models.CharField(...)
And I have these two possibilities of a query in a view:
b_objs = B.objects.filter(aproperty=value)
a_objs = [b.foreign for b in b_objs]
or
a_objs = A.objects.filter(b__aproperty=value)
Are they equally expensive?
Upvotes: 0
Views: 38
Reputation: 25539
They are not only "not equally expensive", but the result is also different.
First approach: You query directly on B
, then get all foreign
by looping on b_objs
. Result is a list.
Second approach: You did a database join
operation in the underline implementation, then fetch the results. Result is a queryset.
Apparently the second approach is more efficient, because you only joined the database once to fetch the result, whereas the first approach you need to hit the database many times to get A
objects.
Upvotes: 3