django - making sections for course

Viewed 96

I am building a site with the logic of Course - Section- Lesson. I can shoot the sections of the course, but I cannot shoot the lessons of the sections. Where am I doing wrong?

Models.py

class CourseCategoryModel(models.Model):
    name = models.CharField(max_length=200, verbose_name="Category Name")
    slug = models.SlugField(unique=True)

class CourseModel(models.Model):
    name = models.CharField(max_length=200, verbose_name="Course Name")
    category = models.ForeignKey(CourseCategoryModel, null=True, blank=True, on_delete=models.PROTECT, verbose_name="Course Category")

class CourseLessonSectionModel(models.Model):
    name = models.CharField(max_length=200, verbose_name="Section Name")
    order = models.IntegerField(max_length=3, verbose_name="Section Order")
    course = models.ForeignKey(CourseModel, null=True, blank=True, on_delete=models.PROTECT, verbose_name="Course")

class CourseLessons(models.Model):
    course = models.ForeignKey(CourseModel, null=True, blank=True, on_delete=models.CASCADE, verbose_name="Course")
    section = models.ForeignKey(CourseLessonSectionModel, null=True, blank=True, on_delete=models.CASCADE, verbose_name="Lesson Section")
    name = models.CharField(max_length=200, verbose_name="Lesson Name")
    order = models.IntegerField(max_length=3 , verbose_name="Lesson Order", default=0)

View.py

def detail(request, slug):
    course = CourseModel.objects.get(slug=slug)

    courseSection = CourseLessonSectionModel.objects.all().filter(course__slug=slug)

    courseLessons = CourseLessons.objects.all().filter("what should i write here?")

    return render(request, "coursedetail.html", context={
        "course": course,
        "courseLessons" : courseLessons,
        "courseSection" : courseSection
    })
1 Answers

You have made ManyToOne relationship which is ForeignKey for everything.

You want to fetch lesson of the sections. I am assuming that you already fetched course and courseSection correctly.

You can __in lookup to filter on all sections' ids with particular course, so:

from django.db.models import Q

def detail(request, slug):
    course = CourseModel.objects.get(slug=slug)

    courseSection = CourseLessonSectionModel.objects.all().filter(kurs__slug=slug)
    course_section_list=list(courseSection)

    courseLessons = CourseLessons.objects.filter(Q(course=course) & Q(section__in=[i.id for i in course_section_list]))

    return render(request, "coursedetail.html", context={
        "course": course,
        "courseLessons" : courseLessons,
        "courseSection" : courseSection
    })
Related