Ticket #20429: upsert.py

File upsert.py, 710 bytes (added by Evan Cofsky, 11 years ago)

Sample implementation of update_or_create.

Line 
1class Manager(models.Manager):
2 """Provides the update_or_create method for regular managers.
3
4 This will call get_or_create, and if an object is not created, it
5 will update the object with the contents of the defaults parameter
6 and save it."""
7
8 def update_or_create(self, **kwargs):
9 obj, created = self.get_or_create(**kwargs)
10 if not created and "defaults" in kwargs:
11 for k, v in kwargs.get("defaults", {}).items():
12 if k not in dir(obj):
13 raise AttributeError("Invalid attribute %s provided for update on %s (%d)" % (k, type(obj), obj.pk))
14
15 setattr(obj, k, v)
16 obj.save()
17
18 return obj, created
Back to Top