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 ?
You should be able to do this, I think.
Warning: not testedTested using local models. Generated query looked good.For this to work there should be a
vehicleforeign key field declared inRoutesmodel. This is ’causeselect_related()only follows forward relationships.