'Django: how to count posts related to a category in django?

i have a model class Category and also a model class Course. i want to count all the courses that are related to a model e.g: Web Devlopment - 26 Courses i dont know how to go about this since the this are two diffrent models.

class Category(models.Model):
    title = models.CharField(max_length=1000)

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)
    course_category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, null=True, blank=True)


Solution 1:[1]

First, you need to set the related_name attribute in the course_category field.

class Course(models.Model):
    ...
    course_category = models.ForeignKey(Category, realted_name="courses" on_delete=models.DO_NOTHING, null=True, blank=True)

Next, you can use this name to aggregate the query as the following.

from django.db.models import Count
cateogries = Category.objects.annotate(number_of_courses = Count("courses")).all()

Then, each of the categories will have the number_of_courses field that indicates the number of courses.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David Lu