2011-06-11 77 views
0

我做过模板处理器使用后向关系。在shell它的工作原理确定,但认为我有一个错误:在在上下文处理器中的关系“向后”处理器

'ParentCategory' object has no attribute 'postpages_set'

模型(比原来稍微简单一些)

class ParentCategory(models.Model): 
    category = models.CharField(max_length = 150) 


class PostPages(models.Model): 
    parent_category = models.ForeignKey('ParentCategory', 
            blank = True, 
            null = True,          
            related_name = "parent_category") 
    title = models.CharField(max_length = 150) 
    text = models.TextField() 

背景处理器

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>: []} 

怎么回事错了吗?这种外壳和视图之间有什么不同?

回答

1

您已明确更名为相关对象管理器,使用related_name,所以它现在被称为parent_category

cat.parent_category.all() 

这当然是一个非常误导的名字 - 我不知道你为什么在设置related_name所有。至于为什么它不出现在shell中,我只能假设你在不重新启动shell的情况下在代码中进行了更改。

最后,不过,我不知道为什么你要做到这一点,你可以很容易地访问相关的对象模板:

{% for category in output_categories %}{{ category.parent_category.all }}{% endfor %} 
+0

谢谢你,我做到了更吸尘器你的建议。有关更多信息,我使用了您的博客。这是相当详细解释。 – I159 2011-06-11 11:25:08