I am trying to access a lesson belonging to a course in my application. When I use the url http://127.0.0.1:8000/courses/1/lessons/1/" the appropriate results get returned. However when I try anyother url such as "http://127.0.0.1:8000/courses/1/lessons/2/" I get an error instead Result for http://127.0.0.1:8000/courses/1/lessons/1/
{
"id": 1,
"title": "course 1 lessson 1",
"owner": 1,
"course": 1
}
Expected Result for http://127.0.0.1:8000/courses/1/lessons/2/
{
"id": 1,
"title": "course 1 lessson 2",
"owner": 1,
"course": 1
}
actual result
{
"detail": "Not found."
}
URL
path('courses/<int:pk>/lessons/<int:lpk>/', LessonDetail.as_view()),
Serializer
class LessonSerializer(serializers.ModelSerializer):
class Meta:
model = Lesson
fields = ['id','title','owner','course']
view
class LessonDetail(generics.RetrieveUpdateDestroyAPIView):
# queryset = Lesson.objects.all()
serializer_class = LessonSerializer
def get_queryset(self):
# GET PK FROM URL USING KWARGS
course_pk = self.kwargs['pk']
lesson_pk = self.kwargs['lpk']
qs = Lesson.objects.filter(course_id=course_pk,id=lesson_pk)
print(qs)
return qs
model
class Lesson(models.Model):
title = models.CharField(max_length=150, help_text='Enter course title')
video = models.CharField(max_length=150, help_text='Enter course title', null=True)
thumbnail = models.CharField(max_length=150, help_text='Enter course title', null=True)
pub_date = models.DateField(null=True, blank=True)
course = models.ForeignKey('Course', on_delete=models.CASCADE,related_name='lessons')
description = models.TextField(max_length=1000, help_text='Enter a brief description of the course')
owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, )
The view returns the object <QuerySet [<Lesson: course 1 lessson 1>]> for http://127.0.0.1:8000/courses/1/lessons/1/
and <QuerySet [<Lesson: course 1 lessson 2>]> for http://127.0.0.1:8000/courses/1/lessons/2/. To my inexperienced eye, it looks as if the view is returning the appropriate queryset but it fails to produce any results for the second url. How can I make it respond appropriately.
You also can use generics.RetrieveAPIView for DetailView. Than declare queryset and serializer_class.