2011-06-11 59 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