Django: select_related () for an existing object?

If I get an object using django, I can use .select_related() to give django the ability to get all the foreign key objects, namely:

 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 .select_related() , that is:

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

Is there a way to get django to populate all its relationships with a foreign key? Sort of:

 def doit(obj): obj.magic() #1 db hit obj.long.chain.of.stuff #no db hits 
+6
source share
1 answer

I believe I can:

 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 a better way?

+3
source

Source: https://habr.com/ru/post/901647/


All Articles