i have a course models and user are allowed to purchase this courses, now i want to filter the courses by the most selling course, i have tried using django agreegate but it seems not to be giving me what i want or maybe i am not doing it the right way.
i have models.py that is storing the courses
class Course(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
course_title = models.CharField(max_length=100, null=True, blank=True)
slug = models.SlugField(unique=True)
course_creayor = models.ForeignKey(User, on_delete=models.CASCADE)
i also have this model that stores the courses that are purchased and enrolled in
class UserCourse(models.Model):
user = models.ForeignKey(User , null = False , on_delete=models.CASCADE)
course = models.ForeignKey(Course , null = False , on_delete=models.CASCADE)
date = models.DateTimeField(auto_now_add=True)
i dont know how to write the view to filter the courses by the most selling
from the image below you can see that learn angular updated
is the most selling course for the creator destiny
. so how do i filter this for each user, thier most selling course?
You can try annotating the course counts like this:
course_counts = UserCourse.objects.values("course").annotate(count=models.Count("course"))
Then sorting:
sorted_courses = sorted(course_counts, key=lambda x: x['count'],reverse=True)
You will have the sorted_courses[0]
containing the highest one and you can retrieve the UUID
from the dict