【问题标题】:Django ORM: avoid multiple queries when saving models with foreign key relationshipsDjango ORM:保存具有外键关系的模型时避免多次查询
【发布时间】:2014-11-27 06:47:05
【问题描述】:

假设我有 3 个模型:ABC,其中 C 具有外键关系AB。 如果我有检索 AB 所需的信息,如何在保存 C 模型时避免多次查询?

目前我的代码是这样的:

a = A.objects.get(title='the title', platform='the platform')
b = A.objects.get(id='the id')
C.objects.update_or_create(a=a, b=b, defaults={'c_param_1':'value'})

这很糟糕,因为它至少执行 3 个查询(如果 C 对象不存在,则为 4 个)。 我想在db层检索ab...如何使用Django的ORM实现?

我目前尝试以这种方式使用 Q 对象:

C.objects.update_or_create(
        a=Q(a__title='the title') & Q(a__platform='the platform'), 
        b=Q(b__id='the id'), 
        c_param_1='value'
)

但我明白了:

TypeError: int() argument must be a string or a number, not 'Q'

ps:我使用的是 Django 1.7

【问题讨论】:

    标签: python django performance django-models orm


    【解决方案1】:

    好吧,由于外键实际上是它所引用的对象的 id,因此您必须运行查询来获取此 id。但是,如果您已经拥有父对象的 id,您可以创建一个不完全加载父对象的子对象:

    C.objects.update_or_create(
        a_id=id_of_a, 
        b_id=id_of_b,
        c_param_1='value'
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-04
      • 1970-01-01
      • 2016-10-12
      • 2020-04-20
      • 2012-02-02
      • 2015-10-11
      • 2011-11-15
      • 1970-01-01
      相关资源
      最近更新 更多