Django - 通过相关字段的ID获取对象

时间:2012-02-25 16:29:52

标签: python django django-models django-queryset

我们假设我们有以下模型:

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模型中foobar字段用作复合键,也就是说,对于任何一对(foobar),只有一个Zomg对象。

在我的项目中,我需要不时更新数千条Zomg条记录,因此查找记录的效率非常重要。问题是我无法将foo_idbar_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_idbar_id几乎可以访问:

>>> z.foo_id
1
>>> z.bar_id
1

现在我不得不首先获取FooBar个对象,然后使用它们获取所需的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个对象?

1 个答案:

答案 0 :(得分:1)

试试这个: z = models.Zomg.objects.get(foo__id=1, bar__id=1)