Home > Mobile >  How to show all the lesson urls present in a lesson list?
How to show all the lesson urls present in a lesson list?

Time:08-21

I would like to retrieve lesson present in chapter model.

class Course(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    description = models.TextField()
    price = models.FloatField()

class Chapter(models.Model):
    title = models.CharField( max_length=200)
    course = models.ForeignKey(Course, on_delete=models.CASCADE)
    is_active = models.BooleanField(default=True)

class Lesson(models.Model):
    chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    video_url = models.URLField()

Below is my views.py:

def courseDetail(request, category_slug, course_slug):
    try:
        course_detail = Course.objects.get(category__slug=category_slug, slug=course_slug)
        all_chapters = Chapter.objects.filter(course=course_detail).order_by('created_date')
        all_lessons = Lesson.objects.filter(chapter__id__in=all_chapters)
    except Exception as e:
        raise e

    context = {
        'course_detail': course_detail,
        'all_chapters': all_chapters,
        'all_lessons': all_lessons,
    }
    return render(request, 'course-detail.html', context)

Here is my urls.py:

urlpatterns = [
    path('<slug:category_slug>/<slug:course_slug>/', views.courseDetail, name='course-detail'),
]

I am trying to explain my issue with the bellow example Ex:

  1. Course: "Course 1"
  2. In that course i have 2 chapters i.e Chapter 1, Chapter 2
  3. And each chapter contains 3 lessons. i.e Chapter 1 contains Lesson 1, Lesson 2, Lesson 3 and Chapter 2 contains Lesson 4, Lesson 5, Lesson 6.

So when I wanted to show respective lessons inside the respective chapters it's showing all the lessons in both the chapters. How to fix this?

CodePudding user response:

Not entirely sure what you want to do but my hunch is replace the following:

all_lesson_urls = LessonURL.objects.filter(category__id__in=all_lessons)

with

all_lesson_urls = LessonURL.objects.filter(category__id__in=all_lessons).values("category__title", "title")

CodePudding user response:

I am assuming that you are getting all_chapters from Chapter model successfully, so to fetch all_lessons from Lesson model, do this query:

all_chapters = Chapter.objects.filter(course=course_detail).order_by('created_date')
list_of_all_chapters=list(all_chapters)
all_lessons = Lesson.objects.filter(chapter__in=[i.id for i in list_of_all_chapters])

Since __in lookup is used to filter in range of values from list.

  • Related