【发布时间】:2014-11-27 06:47:05
【问题描述】:
假设我有 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 个)。 我想在db层检索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
【问题讨论】:
标签: python django performance django-models orm