Home > Enterprise >  Django: how to count posts related to a category in django?
Django: how to count posts related to a category in django?

Time:05-14

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)

CodePudding user response:

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.

  • Related