Reputation: 1934
I'm wondering which, if either, query is faster in Django. I have a Location model and a User model. Users are foreign keyed to Locations, so each Location can have a 'locationuser_set' attribute.
Which, if either, is faster if I have thousands of Users?
Query 1:
location = Location.objects.get(id=<id>)
users = location.user_set.all()
Query 2:
users = User.objects.filter(location_id=<id>)
Upvotes: 3
Views: 766
Reputation: 600026
Query 2 is exactly equivalent to the second line of Query 1. But since Query 1 also includes the first line, which does a separate Location lookup, it is necessarily slower.
If you don't need the actual location object, then 2 is definitely the way to go.
Upvotes: 5