在上下文处理器中“向后”跟随关系

问题描述 投票:0回答:2

我做的template processor用到了backward following relationship。在 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>: []}

怎么了?以这种方式,shell 和 view 之间有什么区别?

django django-queryset django-context
2个回答
1
投票

您已使用

related_name
显式重命名相关对象管理器,因此现在称为
parent_category
:

cat.parent_category.all()

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

related_name

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

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

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

0
投票

查看 django 中的 select_related 和 prefetch_related 查询集方法。 Daniel 提供的解决方案可以工作,但它会执行多个查询。

© www.soinside.com 2019 - 2024. All rights reserved.