在上下文处理器中"backward"跟踪关系



模板处理器使用了后向关系。在shell中它工作正常,但在视图中我有一个错误:

"ParentCategory"对象没有属性"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>: []}

出了什么问题?外壳和视图在这种方式下有什么区别?

您已经使用related_name显式重命名了相关的对象管理器,因此它现在被称为parent_category:

cat.parent_category.all()

这当然是一个非常误导性的名字——我不知道你为什么要设置related_name

至于为什么它没有出现在shell中,我只能假设您在没有重新启动shell的情况下对代码进行了更改。

然而,最后,我不知道你为什么要这样做,因为你可以很容易地访问模板中的相关对象:

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

最新更新