Django Annotate() and Alias() Django.How

Author avatar wrote on 06/06/2022

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

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):

 

Fetch channels with videos count

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

 

Fetch channels that have videos

VideoChannel.objects.annotate(videos_count=Count('video')).filter(videos_count__isnull=False)

 

Fetch channels that have no videos

VideoChannel.objects.annotate(videos_count=Count('video')).filter(videos_count__isnull=True)

 

Fetch channels with no less than 5 videos

VideoChannel.objects.annotate(videos_count=Count('video')).filter(videos_count__gte=5)

 

Fetch channels ordered by number of videos

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

 

Generating aggregates for each item in a QuerySet

from django.db.models import Count
q = Book.objects.annotate(Count('authors')) 

 

This adds to query filed = authors will set how many authors for each book
CRUDgen Django CRUD generator