update_or_create

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from django.db import transaction, IntegrityError

def _update_or_create(self, **kwargs):
    assert kwargs, \
            'update_or_create() must be passed at least one keyword argument'
    obj, created = self.get_or_create(**kwargs)
    defaults = kwargs.pop('defaults', {})
    if created:
        return obj, True, False
    else:
        try:
            params = dict([(k, v) for k, v in kwargs.items() if '__' not in k])
            params.update(defaults)
            for attr, val in params.items():
                if hasattr(obj, attr):
                    setattr(obj, attr, val)
            sid = transaction.savepoint()
            obj.save(force_update=True)
            transaction.savepoint_commit(sid)
            return obj, False, True
        except IntegrityError, e:
            transaction.savepoint_rollback(sid)
            try:
                return self.get(**kwargs), False, False
            except self.model.DoesNotExist:
                raise e

More like this

  1. Ordered items in the database - alternative by Leonidas 4 years, 8 months ago
  2. Configurable defaults for contrib.sites default Site during syncdb by chrischambers 5 months, 1 week ago
  3. DRY Fieldsets by DrMeers 2 years, 8 months ago
  4. Modifying the fields of a third/existing model class by marinho 1 year, 1 month ago
  5. CustomQueryManager by zvoase 3 years, 7 months ago

Comments

(Forgotten your password?)