Home > OS >  How can i combine these two Django annotated queries into one?
How can i combine these two Django annotated queries into one?

Time:11-19

i have two queries:

class Users(models.Model):

name = models.CharField(max_length=50, unique=True)

class Comments(models.Model):

user_field = models.ForeignKey(Users,on_delete=models.PROTECT,db_index=True, to_field='name')
likedislike = models.SmallIntegerField(db_index=True)

bb1 = Users.objects.filter(comments__likedislike__gt=0).annotate(likes=Sum('comments__likedislike'))

bb2 = Users.objects.filter(comments__likedislike__lt=0).annotate(dislikes=Sum('comments__likedislike'))

how to combine them?

CodePudding user response:

You can pass a filter to Sum to restrict which values are used, you can then have two filtered annotations in the same query

from django.db.models import Sum, Q
Users.objects.annotate(
    likes=Sum('comments__likedislike', filter=Q(comments__likedislike__gt=0)),
    dislikes=Sum('comments__likedislike', filter=Q(comments__likedislike__lt=0))
)
  • Related