views:

34

answers:

2

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 ?

+2  A: 

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.

Manoj Govindan
It works. I thought I had tried this before, but apparently, I must have made a mistake. I have checked that the sql queries are fetching just what is needed. Thanks !
madewulf
BTW, in fact, your code is equivalent to my "ideal code" .... My question was self answered. Sorry ...
madewulf
@madewulf: don't be! Writing the question out crystallizes thought. And in the process we often figure out the solution :)
Manoj Govindan
+1  A: 

You can try following:

Routes.objects.filter(scheduleid__id=schedule.id).values('externalid', 'vehicle__name')
Dominik Szopa