use-annotate-aggrgation-in-django

How to use annotate aggregation in django

Hello World, Welcome to ProjectsPlaza.com. Today we will discuss how to use annotate aggregation in Django. In this tutorial, we will fetch data from two different models. For example, I am creating a video sharing website like YouTube. I have two models. One is a channel and another is a video. Both models are joined with foreign keys. Now I want to fetch channels with videos count. I will do this with annotate aggregation.


Channel Model

# Channel
class VideoChannel(models.Model):
    user=models.ForeignKey(User,on_delete=models.CASCADE)
    name=models.CharField(max_length=200)
    detail=models.TextField()

    def __str__(self):
        return self.name

Video Model

# Videos
class Video(models.Model):
    user=models.ForeignKey(User,on_delete=models.CASCADE)
    channel=models.ForeignKey(VideoChannel,on_delete=models.CASCADE,null=True)
    src=models.FileField(upload_to='videos/')
    title=models.CharField(max_length=200,help_text='Enter Title')

    def __str__(self):
        return self.title

Fetch channels with videos count

We want to fetch videos count the same as the following screen.

annotate aggregation example in django

We can fetch this result with the help of the following code.

VideoChannel.objects.annotate(videos_count=Count('video')).all()

I hope you have enjoyed this tutorial. Please add your feedback in the comment section.

Leave a Reply

Your email address will not be published. Required fields are marked *