I am building a website where an instructor can create courses and students can enroll the courses. Is there any way to display top 3 most enrolled courses by students that an instructor has created?
I have tried using .values().annotate().order_by()[] but it seems that i cant display it on template.
models.py
class Enrollment(models.Model):
student = models.ForeignKey(User, on_delete=models.CASCADE)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
enrollment_date = models.DateField(auto_now_add=True, null = True)
class Course(models.Model):
user = models.ForeignKey(Users, on_delete = models.CASCADE)
media = models.ImageField(upload_to = 'media/course')
title = models.CharField(max_length=300, null = False)
subtitle = models.CharField(max_length=500, null = False)
description = models.TextField(max_length=5000, null = False)
language = models.CharField(max_length=20, null = False, choices=LANGUAGE)
level = models.CharField(max_length=20, null = False, choices=LEVEL)
category = models.CharField(max_length=30, null = False, choices=CATEGORY)
subcategory = models.CharField(max_length=20, null = False)
price = models.FloatField(null = True)
roles_responsibilities = models.TextField(max_length=2500, null = False)
timeline_budget = models.TextField(max_length=250, null = False)
req_prerequisite = models.TextField(max_length=2500, null = False)
certificate = models.CharField(max_length=5, null = False, choices=CERTIFICATE)
slug = AutoSlugField(populate_from='title', max_length=500, unique=True, null=True)
views.py
def instructorDashboard(request):
student = Enrollment.objects.filter(course__in=course)
popular_courses= student.values('course__title').annotate(count=Count('course__title')).order_by('-count')[:3]
print(popular_courses)
context = {
'popular_courses': popular_courses,
}
return render(request, 'instructor_dashboard/index.html', context)
index.html
<!-- Popular Courses -->
<div class="col-xl-4 col-lg-5">
<div class="card shadow mb-4">
<!-- Card Header - Dropdown -->
<div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
<h6 class="m-0 font-weight-bold text-primary">Popular Courses</h6>
</div>
{% for popular_course in popular_courses %}
<div class="card-body">
{{ course.title }}
</div>
{% endfor %}
</div>
</div>