Skip to main content
 首页 » 编程设计

python之Django ORM : avoid multiple queries when saving models with foreign key relationships

2025年05月04日20lovecherry

假设我有 3 个模型:A、B、C,其中 C 具有外键关系同时包含 A 和 B。 如果我有必要的信息来检索 A 和 B,在保存 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 次)。 我想在数据库层检索 a 和 b ...如何使用 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

请您参考如下方法:

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

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