2

I have a model:

class A(models.Model):
    name = models.CharField()
    price = models.IntegerField()

I need to aggregate Sum of all records in db but before it I want to remove duplicates by name (distinct)

So i try use

 A.objects.all().distinct('name').aggregate(total=Sum('price')

But I got error

NotImplementedError: aggregate() + distinct(fields) not implemented.

So, How can I achieve same result in django orm?

Example of table:
| name | price |
  Nick | 100 |
  Eva  | 200 |
  Nick | 100 |

I want to select all unigue values by name and than Sum price. The result is a simple number. 300 in this example.

Yura Bysaha
  • 721
  • 6
  • 17

3 Answers3

2

no i dont try but if ur table -A- like this :

| name | price |
  Nick | 100 |
  Nick | 100 |
  Nick | 100 |
  Eva  | 200 |
  Eva  | 200 |
  Nick | 100 |

the queryset : A.objects.all().values('name').annotate(total=Sum('price')) will give u dict like this :

[{'Nick':400},{'Eva':400}]

try use F() objects:

from django.db.models import Sum, F

A.objects.all().values('name').annotate(total=Sum(F('price')))
Salim Fh
  • 75
  • 6
0

You are probably using sqlite as db backend which does not support distinct on fields The Query

A.objects.all().distinct('name')

would have raised a

NotSupportedError('DISTINCT ON fields is not supported by this database backend')

exception anyway

Ismael
  • 86
  • 6
0
 A.objects.all().values('name').annotate(total=Sum('price'))

try

Salim Fh
  • 75
  • 6