[Answered ]-Get model ID correctly

2đź‘Ť

âś…

You just filter by the alias on MainMenuItem then get all articles that related to that MainMenuItem:

def menu_builder(request, alias):
    main_menu_item = MainMenuItem.objects.get(alias=alias)
    elements = {
            'menuItems': main_menu_item,
            'articles': main_menu_item.article_set.all(),
        }
    return render_to_response('myview.html, elements)

Django doc about related object lookup using _set.

Edit:

I should have been using objects.get() previously, but was using objects.filter() which is wrong. The difference is that you should get exactly one item so that you could get related articles to that object. If you use filter, you would end up having a queryset, but then it doesn’t make sense to check related objects on multiple objects, hence the error 'QuerySet' object has no attribute 'article_set'.

Beware that you should have distinct alias for MainMenuItem objects, otherwise get() would throw an exception “Multiple objects returned”.

👤Shang Wang

Leave a comment