【问题标题】:django: select_related() on an already-existing object?django: select_related() 在一个已经存在的对象上?
【发布时间】:2011-12-30 17:11:43
【问题描述】:

如果我正在使用 django 检索对象,我可以使用 .select_related() 来指示 django 也获取所有外键对象:

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

如果我已经有obj,而没有.select_related(),那就是:

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

有没有办法让 django 填写它所有的外键关系?比如:

def doit(obj):
    obj.magic() #1 db hit
    obj.long.chain.of.stuff #no db hits

【问题讨论】:

    标签: python sql database django performance


    【解决方案1】:

    我想我可以做到:

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

    但是有没有更好的方法呢?

    【讨论】:

    • 我认为这将是您唯一的方法。不过,我会确保对那段代码进行注释,这样以后看到它的任何人都不会挠头想知道为什么这样做,或者更糟糕的是,删除它,因为它看起来多余。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 2016-03-25
    • 2015-08-31
    • 2021-12-31
    • 2016-06-12
    • 2010-12-21
    • 1970-01-01
    相关资源
    最近更新 更多