Django “以下关系”;“向后”;上下文处理器
我不知道模板处理器使用了向后跟踪关系。在shell中工作正常,但在视图中我有一个错误: “ParentCategory”对象没有属性“postpages\u set” 模型(比原模型简单一点) 上下文处理器Django “以下关系”;“向后”;上下文处理器,django,django-queryset,django-context,Django,Django Queryset,Django Context,我不知道模板处理器使用了向后跟踪关系。在shell中工作正常,但在视图中我有一个错误: “ParentCategory”对象没有属性“postpages\u set” 模型(比原模型简单一点) 上下文处理器 from shivablog.shivaapp.models import ParentCategory def menu_items(request): output_categories = {} category_list = ParentCategory.objec
from shivablog.shivaapp.models import ParentCategory
def menu_items(request):
output_categories = {}
category_list = ParentCategory.objects.all()
for category in category_list:
output_categories[category] = category.postpages_set.all()
return {'output_categories': output_categories}
在外壳中:
>>> output = {}
>>> cat_list = ParentCategory.objects.all()
>>> for cat in cat_list:
... output[cat] = cat.postpages_set.all()
...
>>> output
{<ParentCategory: category#1>: [<PostPages: Post 1>, <PostPages: post 2>], <ParentCategory: category #2>: [], <ParentCategory: category #3>: []}
>>输出={}
>>>cat_list=ParentCategory.objects.all()
>>>对于cat_列表中的cat:
... 输出[cat]=cat.postpages\u set.all()
...
>>>输出
{: [, ], : [], : []}
出什么事了?在这种方式下,shell和view有什么不同 您已使用
related\u name
明确重命名了related objects manager,因此它现在被称为parent\u category
:
cat.parent_category.all()
这当然是一个非常容易引起误解的名称-我根本不知道您为什么要设置相关的名称
至于为什么它没有出现在shell中,我只能假设您在没有重新启动shell的情况下对代码进行了更改
但最后,我不知道您为什么要这样做,因为您可以轻松访问模板中的相关对象:
{% for category in output_categories %}{{ category.parent_category.all }}{% endfor %}
谢谢你,听了你的建议,我做得更干净了。更多信息,我用了你的博客。解释得很详细。
{% for category in output_categories %}{{ category.parent_category.all }}{% endfor %}