Reputation: 1910
I have the following code, using Django ORM
routes =Routes.objects.filter(scheduleid=schedule.id).only('externalid')
t_list = [(route.externalid, route.vehicle.name) for route in routes])
and it is very slow, because the vehicle objects are huge (dozens of fields, and I cannot change that, it is coming from a legacy database). A lot of time is devoted to create the Vehicle objects, while I only need the name field of this object.
Is there a more efficient way to obtain t_list ? I am looking for something like only() for accessing objects through a foreign key.
EDIT : the solution is the following :
routes=Routes.objects.filter(scheduleid=schedule.id).select_related("vehicle")
routes= routes.only('externalid','vehicle__name')
Does there exist something similar ?
Upvotes: 1
Views: 253
Reputation: 1929
You can try following:
Routes.objects.filter(scheduleid__id=schedule.id).values('externalid', 'vehicle__name')
Upvotes: 1
Reputation: 74765
You should be able to do this, I think. Warning: not tested Tested using local models. Generated query looked good.
routes = Routes.objects.select_related('vehicle').filter(**conditions).only(
'externalid', 'vehicle__name')
For this to work there should be a vehicle
foreign key field declared in Routes
model. This is 'cause select_related()
only follows forward relationships.
Upvotes: 2