0

models.py

class Iso(models.Model):
    service_type = models.CharField(max_length=100, blank=True, null=True)
    field_1 = models.IntegerField(blank=True, null=True)
    field_1_size = models.IntegerField(blank=True, null=True)
    field_2 = models.IntegerField(blank=True, null=True)
    field_2_size = models.IntegerField(blank=True, null=True)

In my views.py I have two queryset as follows, now if I want to combine together the queries and if user enters the field_1 value and field_2 value same, it should be summarized.

qs1 = Model.objects.values('service_type', 'field_1')\
            .annotate(field_total=Sum('field_1_size'))
qs2 = Model.objects.values('service_type', 'field_2')\
            .annotate(field_total=Sum('field_2_size'))

I tried, qs_tot = qs1.union(qs2) it combines queryset but not gives a sum value, if the field_1 and field_2 are same. Any helps will be greatly appreciated. Thank you.

bmons
  • 3,352
  • 2
  • 10
  • 18
  • Possible duplicate of [Django ORM, sum of multiple columns](https://stackoverflow.com/questions/43323724/django-orm-sum-of-multiple-columns) – Kevin He Nov 14 '18 at 18:13
  • No, it is just adding two fields only irrespective of the values list, I want the sum of two fields if its field_1 value is same as field_2 value – bmons Nov 14 '18 at 19:04

1 Answers1

0

I think this should work for you. You might have to change it to fit your needs, but it shows the concept of using Case within a Sum annotation.

Model.objects.annotate(
    same_total=Sum(
        Case(
            When(
                field_1=F('field_2'),
                then=F('field_1_size')+F('field_2_size'),
            ), output_field=IntegerField(),
        )
    )
)
schillingt
  • 13,493
  • 2
  • 32
  • 34
  • Could you advise me if it is not equal how to sum up the individual values? Thank you – bmons Nov 15 '18 at 08:45
  • Sorry, I don't understand. – schillingt Nov 15 '18 at 13:51
  • I am looking for sum value of all the instances of the fields, if one field_size value is same as that of the other it should be added, otherwise it should give the sum of individual fields based on its size. – bmons Nov 15 '18 at 17:37
  • You should be able to add additional `Sum` annotations with a different `When` clause to do that. – schillingt Nov 15 '18 at 18:11
  • could you please tell me how to write field1 is not equal to field2 – bmons Nov 15 '18 at 19:48
  • `~Q(field_1=F('field_2'))`. The `~` operator inverts the query filter since Django doesn't support a `!=` operator. – schillingt Nov 15 '18 at 19:53