Search code examples
djangodjango-modelsdjango-querysetdjango-annotate

Combine 2 object of same model Django


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


Solution

  • 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.