0

Is there any way to combine/merge 2+ objects of the same model to 1 with total values of all field.

I mean like Author.objects.annotate(Sum('book__pages')) but for all fields in model.

1 object - {'user':2, 'events':20, 'time': 233}

2 object - {'user':2, 'events':10, 'time': 400}

need total - {'user':2, 'events':30, 'time': 633}

thx

Beliaf
  • 577
  • 2
  • 8
  • 25

1 Answers1

1

You can use values() and then annotate().

MyModel.objects.values('user').annotate(
    total_events=Sum('events'),
    total_time=Sum('time'),
)

See the Django docs for more info.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • is this the only way to count total values? Not the best one for me, as i have mannualyy type every value from the model. – Beliaf Apr 27 '18 at 07:32
  • If you don’t want to type out the fields, you could introspect the model to create a dict `kwargs={'total_events': Sum('events'), ...}`, then call `.annotate(**kwargs)`. – Alasdair Apr 27 '18 at 07:49
  • so i can create `kwargs ={'total_field_name': Sum('field_name'), ... +12 fields} ` and then call on model query set `.annotate(**kwargs)`. – Beliaf Apr 27 '18 at 09:47
  • Yes, that's what I was suggesting. – Alasdair Apr 27 '18 at 09:48
  • And if you don't want to hardcode the field names, you can introspect the model using the [Meta API](https://docs.djangoproject.com/en/2.0/ref/models/meta/). – Alasdair Apr 27 '18 at 09:55