django 1.6 - 获取相关对象的相关对象

时间:2017-01-30 12:36:56

标签: django

我有以下三种模式:

class Region(models.Model):
    code = models.IntegerField()

class ReportRequest(models.Model):
    # a report can include many regions
    regions = models.ManyToManyField(Region)

class Office(models.Model):
    # an office belongs to one region
    region =  models.ForeignKey(Region)
基本上,许多报告可以有很多地区,一个地区可以有很多办事处。 如何在一个查询中将所有办公室与我的报告的区域相关联?

我可以通过两个查询来执行此操作:

region_pks = reportrequest.regions.values_list('id', flat=True)
offices = Office.objects.filter(region_id__in=region_pks)

但我觉得必须有一种方法可以在一个查询中执行此操作。

如果这是一个由ForeignKeys连接的对象链,我知道如何做到这一点,但ManyToManyField让我感到困惑。

更新

这种方式Office.objects.filter(region__in=reportrequest.regions)不起作用。

reportrequest = ReportRequest.objects.first()
print(Office.objects.filter(region__in=reportrequest.regions).all())

Traceback (most recent call last):
  File "/Users/9999/_projects/declarator/transparency/transparency/scripts/process_report_requests.py", line 22, in <module>
    print(Office.objects.filter(region__in=reportrequest.regions).all())
  File "/Users/9999/.virtualenvs/transparency/lib/python2.7/site-packages/django/db/models/manager.py", line 92, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Users/9999/.virtualenvs/transparency/lib/python2.7/site-packages/django/db/models/query.py", line 691, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "/Users/9999/.virtualenvs/transparency/lib/python2.7/site-packages/modeltranslation/manager.py", line 338, in _filter_or_exclude
    return super(MultilingualQuerySet, self)._filter_or_exclude(negate, *args, **kwargs)
  File "/Users/9999/.virtualenvs/transparency/lib/python2.7/site-packages/django/db/models/query.py", line 709, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "/Users/9999/.virtualenvs/transparency/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1287, in add_q
    clause, require_inner = self._add_q(where_part, self.used_aliases)
  File "/Users/9999/.virtualenvs/transparency/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1314, in _add_q
    current_negated=current_negated, connector=connector)
  File "/Users/9999/.virtualenvs/transparency/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1142, in build_filter
    value, lookups = self.prepare_lookup_value(value, lookups, can_reuse)
  File "/Users/9999/.virtualenvs/transparency/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1047, in prepare_lookup_value
    value = value()
  File "/Users/9999/.virtualenvs/transparency/lib/python2.7/site-packages/django/db/models/fields/related.py", line 839, in __call__
    manager = getattr(self.model, kwargs.pop('manager'))
KeyError: u'manager'

1 个答案:

答案 0 :(得分:1)

offices = Office.objects.filter(region__in=reportrequest.regions.all())