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
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With