Home > Mobile >  Using Filter or Q in Aggregation
Using Filter or Q in Aggregation

Time:03-18

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']

CodePudding user response:

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))
)
  • Related