我们假设我们有以下模型:
from django.db import models
class Foo(models.Model):
name = models.CharField(max_length=50)
class Bar(models.Model):
name = models.CharField(max_length=50)
class Zomg(models.Model):
foo = models.ForeignKey(Foo)
bar = models.ForeignKey(Bar)
在Zomg
模型中foo
和bar
字段用作复合键,也就是说,对于任何一对(foo
,bar
),只有一个Zomg
对象。
在我的项目中,我需要不时更新数千条Zomg
条记录,因此查找记录的效率非常重要。问题是我无法将foo_id
和bar_id
传递给Zomg.objects.get()
方法:
>>> z = models.Zomg.objects.get(foo_id=1, bar_id=1)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/django/db/models/manager.py", line 132, in get
return self.get_query_set().get(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/db/models/query.py", line 341, in get
clone = self.filter(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/db/models/query.py", line 550, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/db/models/query.py", line 568, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/usr/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1194, in add_q
can_reuse=used_aliases, force_having=force_having)
File "/usr/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1069, in add_filter
negate=negate, process_extras=process_extras)
File "/usr/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1260, in setup_joins
"Choices are: %s" % (name, ", ".join(names)))
FieldError: Cannot resolve keyword 'foo_id' into field. Choices are: bar, foo, id
但是,当对象被实例化时,foo_id
和bar_id
几乎可以访问:
>>> z.foo_id
1
>>> z.bar_id
1
现在我不得不首先获取Foo
和Bar
个对象,然后使用它们获取所需的Zomg
对象,从而进行两次不必要的数据库查询:
>>> f = models.Foo.objects.get(id=1)
>>> b = models.Bar.objects.get(id=1)
>>> z = models.Zomg.objects.get(foo=f, bar=b)
所以问题是,如何通过相关字段的ID获取Zomg
个对象?
答案 0 :(得分:1)
试试这个:
z = models.Zomg.objects.get(foo__id=1, bar__id=1)