from collections import Counter
a = [{'id': '1', 'qty': 6}, {'id': '2', 'qty': 1}, {'id': '1', 'qty': 1}, {'id': '2', 'qty': 1}, {'id': '3', 'qty': 10}, {'id': '1', 'qty': 1}]
c = sum((Counter({d['id']: d['qty']}) for d in a), Counter())
result = [dict(id=k, qty=v) for k, v in c.items()]
from django.db import models
class SingletonModel(models.Model):
"""Singleton model for global settings for example."""
class Meta:
abstract = True
def save(self, *args, **kwargs):
"""Save with id=1."""
self.pk = 1
super(SingletonModel, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
"""Can't delete by default."""
pass
@classmethod
def load(cls):
"""Load value from model."""
obj, created = cls.objects.get_or_create(pk=1)
return obj