[SOLVED] Using Filter or Q in Aggregation

Issue

class Streamer(models.Model):
    name = models.CharField(max_length=50, null=True)
    is_working_with_us = models.BooleanField(default=False)

class Account(models.Model):
    streamer = models.ForeignKey(Streamer, on_delete=models.CASCADE)
    salary= models.Decimalfield(decimal_places=2, max_digits=7)
    cost= models.Decimalfield(decimal_places=2, max_digits=7)

Can I make two different aggregations that depend on attributes in a single query? like below.

streamer_salary_stats = Streamer.objects.filter(is_working_with_us=True).aggregate(
  expensive_streamers_sum=Sum(Q(cost__gt=10000.0),'salary'), # with Q or 
  cheap_streamers_sum=Sum(cost__lte=10000.0,'salary'),  # without Q
)

I know it can be done this way but want to achieve this in a single query.

expensive_streamers_sum = Streamer.objects.filter(
    is_working_with_us=True, cost__gt=10000.0
).aggregate(s=Sum('salary'))['s']
cheap_streamers_sum = Streamer.objects.filter(
    is_working_with_us=True, cost__lte=10000.0
).aggregate(s=Sum('salary'))['s']

Solution

You can use a filter=… parameter [Django-doc]:

streamer_salary_stats = Streamer.objects.filter(is_working_with_us=True).aggregate(
  expensive_streamers_sum=Sum('salary', filter=Q(cost__gt=10000.0)),
  cheap_streamers_sum=Sum('salary', filter=Q(cost__lte=10000.0))
)

Answered By – Willem Van Onsem

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

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