我有以下两种模式:
Class Foo(models.model):
param1 = ...
param2 = ...
...
paramN = ...
Class Bar(models.model):
foo = models.ForeignKey(Foo)
...
...
目标:计算所有Foo实例的QuerySet,以便连接多个Bar实例
我一直在寻找解决方案,这似乎适用于其他所有人
Foo.objects.annotate(num_bar=Count('bar')).filter(num_bar__gt=1)
这给了我一个FieldError
说'bar'
不是Foo
的可能字段,然后我尝试了'bar_set'
并且也得到了相同的错误
我是否有可能错误地执行它们,或者因为它们已经老了它们现在已经被折旧了?任何帮助将不胜感激!
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/ryan/.virtualenvs/project/local/lib/python2.7/site-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/ryan/.virtualenvs/project/local/lib/python2.7/site-packages/django/db/models/query.py", line 794, in annotate
obj.query.add_annotation(annotation, alias, is_summary=False)
File "/home/ryan/.virtualenvs/project/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 982, in add_annotation
summarize=is_summary)
File "/home/ryan/.virtualenvs/project/local/lib/python2.7/site-packages/django/db/models/aggregates.py", line 20, in resolve_expression
c = super(Aggregate, self).resolve_expression(query, allow_joins, reuse, summarize)
File "/home/ryan/.virtualenvs/project/local/lib/python2.7/site-packages/django/db/models/expressions.py", line 491, in resolve_expression
c.source_expressions[pos] = arg.resolve_expression(query, allow_joins, reuse, summarize, for_save)
File "/home/ryan/.virtualenvs/project/local/lib/python2.7/site-packages/django/db/models/expressions.py", line 448, in resolve_expression
return query.resolve_ref(self.name, allow_joins, reuse, summarize)
File "/home/ryan/.virtualenvs/project/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1532, in resolve_ref
self.get_initial_alias(), reuse)
File "/home/ryan/.virtualenvs/project/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1471, in setup_joins
names, opts, allow_many, fail_on_missing=True)
File "/home/ryan/.virtualenvs/project/local/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1396, in names_to_path
"Choices are: %s" % (name, ", ".join(available)))
FieldError: Cannot resolve keyword 'bar' into field. Choices are: param1, param2, param3, ..., paramN
我的django版本是1.8.3
答案 0 :(得分:0)
此错误可能有多种原因,我会尝试说明可能的原因:
num_model
。还要检查你是否能得到它们的数量(脏路:) :):
for foo in Foo.objects.all():
if foo.bar_set.count() < 2:
#do sth like : foo.bar_set.get() or temp = temp + 1
截至您对模型的简短描述(不是您的主要代码),找不到其他原因。您的查询应该有效。
答案 1 :(得分:0)
因此,在尝试了很多之后,这是一个有效的解决方案:
Bar.objects.values("foo_id").annotate(Count("foo_id")).filter(pk__count__gt=1)
不完全确定为什么这样做而另一个没有,但它基本上只获得具有相同Bar
的{{1}}个对象的数量,并确保有超过1个。
如果有人想解释为什么这种方法有效而另一方没有解释,那将是值得赞赏的。
答案 2 :(得分:0)
我因导入错误而遇到同样的问题。这是我用例的解决方案
# from django.db.models.sql.aggregates import Count # wrong import
from django.db.models import Count # correct one