'Django: The QuerySet value for an exact lookup must be limited to one result using slicing

i am tring to access a page using a slug url, but i keep getting this error The QuerySet value for an exact lookup must be limited to one result using slicing. i thought it would be a filter or get error in my view but i don't know where the error is coming from

view.py

def tutorial_topic_category(request, slug):
    tutorial_category = TutorialCategory.objects.get(slug=slug)
    tutorial_topic_category = TutorialTopicCategory.objects.filter(tutorial_category=tutorial_category)

    context = {
        'tutorial_topic_category': tutorial_topic_category,
    }
    return render(request, 'tutorials/tutorial_topic_category.html', context)

def topic(request, slug, slug2):
    tutorial_category = TutorialCategory.objects.get(slug=slug)
    tutorial_topic_category = TutorialTopicCategory.objects.filter(tutorial_category=tutorial_category)

    topic = Topic.objects.get(slug=slug2, tutorial_topic_category=tutorial_topic_category)

    context = {
        'topic': topic,
    }
    return render(request, 'tutorials/topic.html', context)

urls.py

path("<slug>", views.tutorial_topic_category, name='tutorial-topic-category'),
path("<slug>/<slug2>", views.topic, name='topic')

and how do i pass in the slug in my template using django template tag

<a href="{% url 'tutorials:topic' category.slug category.slug2  %}">


Solution 1:[1]

In your topic view you are using a filter to get tutorial topic category. This returns a queryset rather than a single item. When you then use it to get 'topic' you are querying based on this set rather than a single equivalent, raising the error. So, instead, to only use the first of the filtered set you could say

topic = Topic.objects.get(slug=slug2, tutorial_topic_category=tutorial_topic_category[0])

...or, if you want to use the full set even though you are only looking for one item

topic = Topic.objects.get(slug=slug2, tutorial_topic_category__in = tutorial_topic_category)

You may also need to to tweak your URL so slug2 comes from the topic slug, as that is the model it will be used to locate the instance of eg:

<a href="{% url 'tutorials:topic' category.slug topic.slug2  %}">

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1