djangodjango-querysetdjango-context

Following relationships "backward" in context processor


I did template processor uses the backward following relationship. In the shell it works OK, but in the view I have an error:

'ParentCategory' object has no attribute 'postpages_set'

model (a little simpler than the original)

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()

context processor

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}

in the shell:

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

What is going wrong? What the differece between shell and view in this way?


Solution

  • You have explicitly renamed the related objects manager, using related_name, so it is now called parent_category:

    cat.parent_category.all()
    

    This is of course a very misleading name - I don't know why you have set related_name at all.

    As for why it doesn't appear in the shell, I can only assume you made the changes in the code without restarting your shell.

    Finally, however, I don't know why you want to do this, as you can just as easily access the related objects in the template:

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