我有一对带外键的 Django 模型,其中一个可以用 django-fts 搜索,比如:
class Foo(models.Model):
...
class Bar(fts.SearchableModel):
foo = models.ForeignKey(Foo)
当我有一个 Foo 实例时,我可以在 View 中插入 print foo.bar_set.all()
并且我会看到一组结果。但是,如果我尝试通过以下任何一种方式在 View 中使用它:
{{foo.bar_set|pprint}}
{{foo.bar_set.all|ppring}}
{{foo.bar_set.count}}
{{foo.bar_set.all|length}}
{% for bar in foo.bar_set.all %} {{bar}} {% endfor %}
从字面上看,我能想到的任何构造的行为就好像foo
实例没有bar_set
属性一样。
编辑:我确定我在模板中有一个 Foo
实例,我测试了以下内容以按预期工作:
{{foo|pprint}}
{{foo.id}} (and any other simple attributes of Foo)
我确定存在相关的 Bar 对象,因为我从 View 中检查了它 (print foo.bar_set.all()
)。如果 QuerySet 为空,{{foo.bar_set.all|pprint}}
将生成 []
,而不是 ''
(它在 {{foo.bar_set.all|pprint}}
、{{foo.bar_set|pprint}}
和任何 {{foo.nonexistent_attribute|pprint }}
).
当我使用 psycopg2 驱动程序将开发从 SQLite 数据库转移到 PostgreSQL 以使用 django-fts 全文搜索时,这种行为就开始了。
我找不到任何其他答案,因为谷歌搜索这非常困难:“反向关系”或“反向外键”都散落着不相关的 django.core.urlresolvers.reverse
引用,并且我不知道如何将“*_set”命名为 Google。关于如何用谷歌搜索这个的提示也会有所帮助。
最佳答案
感谢Marcin Kaszyński在 SO 的帮助下,我设法将错误追溯到 django-fts基地经理。 Django-fts 是一个全文搜索引擎,增加了 .search(query)
可搜索类管理器的方法,我可以写 Foo.objects.search("bar")
.为了方便,它添加了__call__
管理器的方法,由 RelatedManager
继承(其中的实例是 bar_set
)。
模板代码,在<a href="http://code.djangoproject.com/browser/django/trunk/django/template/__init__.py?rev=10519#L701" rel="noreferrer noopener nofollow">django.templates.Variable._resolve_lookup</a>
中方法,看到 bar_set
是可调用的(第 717 行),尝试不带参数调用它(第 722 行),并将该变量视为空变量,因为需要参数(第 724-726 行)。
Removing the __call__ method from django-fts' BaseManager有帮助。
关于django - 反向外键到模板中的 django-fts 可搜索模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1142411/