Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django: select_related() on an already-existing object?

If I am retrieving an object with django, I can use .select_related() to instruct django to get all foreign key objects as well, to wit:

obj = ModelClass.objects.select_related().get(id=4) #1 db hit
foo = obj.long.chain.of.stuff #no db hit

If I already have obj, without it having been .select_related(), that is:

def doit(obj):
    obj.long.chain.of.stuff #4 db hits

is there any way to get django to fill in all of its foreign key relations? Something like:

def doit(obj):
    obj.magic() #1 db hit
    obj.long.chain.of.stuff #no db hits
like image 599
Claudiu Avatar asked Nov 16 '11 18:11

Claudiu


1 Answers

I suppose I can do:

def doit(obj):
    obj = obj.__class__.objects.select_related().get(id=obj.id) #1 db hit
    obj.long.chain.of.stuff #no db hits

But is there any nicer way?

like image 96
Claudiu Avatar answered Nov 08 '22 18:11

Claudiu