2

我有一对带有外键的 Django 模型,其中一个可以用 django-fts 搜索,比如:

class Foo(models.Model):
    ...
class Bar(fts.SearchableModel):
    foo = models.ForeignKey(Foo)

当我有一个 Foo 的实例时,我可以在视图中插入print foo.bar_set.all()并看到一组结果。但是,如果我尝试通过以下任何方式在视图中使用它:

{{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 对象,因为我从视图 ( print foo.bar_set.all()) 中检查了这一点。如果 QuerySet 为空,{{foo.bar_set.all|pprint}}将 yield [], not ''(它在{{foo.bar_set.all|pprint}},{{foo.bar_set|pprint}}和 any上执行{{foo.nonexistent_attribute|pprint}})。

当我使用 psycopg2 驱动程序将开发从 SQLite 数据库转移到 PostgreSQL 以使用 django-fts 全文搜索时,这种行为就开始了。

我找不到任何其他答案,因为谷歌搜索非常困难:“反向关系”或“反向外键”到处都是不相关的django.core.urlresolvers.reverse引用,我不知道如何将“*_set”的东西命名为谷歌。关于如何用谷歌搜索这个的提示也会有所帮助。

4

3 回答 3

2

Thanks to Marcin Kaszyński's help off the SO I managed to trace the bug down to django-fts BaseManager. Django-fts is a full-text search engine, that adds .search(query) method to manager of searchable classes, co I can write Foo.objects.search("bar"). For convenience, it adds __call__ method to the manager, which is inherited by RelatedManager (instance of which is the bar_set).

The template code, in django.templates.Variable._resolve_lookup method, sees that bar_set is callable (line 717), tries to call it with no arguments (line 722), and treats the variable as empty because arguments were required (lines 724-726).

Removing the __call__ method from django-fts' BaseManager helps.

于 2009-07-17T11:58:08.703 回答
0

{{ foo.bar_set.all }}绝对应该工作。你确定你真的有一个 Foo 的实例吗?

于 2009-07-17T10:10:53.223 回答
0

I suggest attempting to pass foo.bar_set.all as a dictionary element in the view function before rendering the page to see if you get the same result.

于 2009-07-17T10:22:42.123 回答