Let's assume we have following models:
我们假设我们有以下模型:
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)
In Zomg
model foo
and bar
fields serve as composite key, that is, for any pair of (foo
, bar
) there is only one Zomg
object.
在Zomg模型中,foo和bar字段用作复合键,也就是说,对于任何一对(foo,bar),只有一个Zomg对象。
In my project I need to update thousands of Zomg
records from time to time, so efficiency of finding records is important. The problem is that I cannot just pass foo_id
and bar_id
to Zomg.objects.get()
method:
在我的项目中,我需要不时更新数千个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
However, when the object is instantiated foo_id
and bar_id
are pretty much accessible:
但是,当对象被实例化时,foo_id和bar_id几乎可以访问:
>>> z.foo_id
1
>>> z.bar_id
1
Now I'm forced to get Foo
and Bar
objects first and then use them to get the required Zomg
object, making two unnecessary database queries:
现在我*首先获取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)
So the question is, how can I get Zomg
object by its related fields' IDs?
所以问题是,如何通过相关字段的ID获取Zomg对象?
1 个解决方案
#1
1
Try this: z = models.Zomg.objects.get(foo__id=1, bar__id=1)
试试这个:z = models.Zomg.objects.get(foo__id = 1,bar__id = 1)
#1
1
Try this: z = models.Zomg.objects.get(foo__id=1, bar__id=1)
试试这个:z = models.Zomg.objects.get(foo__id = 1,bar__id = 1)