Skip to content

Instantly share code, notes, and snippets.

@jorgenschaefer
Last active August 29, 2015 14:06
Show Gist options
  • Save jorgenschaefer/33495c490724a12f1c49 to your computer and use it in GitHub Desktop.
Save jorgenschaefer/33495c490724a12f1c49 to your computer and use it in GitHub Desktop.
class UpdateOrCreateMixin(object):
"""Mixin-Class for models.Manager subclasses.
Provide the update_or_create method from Django 1.7 in earlier
Djangos.
"""
def update_or_create(self, defaults=None, **kwargs):
"""A convenience method for updating an object with the given kwargs,
creating a new one if necessary. The defaults is a dictionary
of (field, value) pairs used to update the object.
Returns a tuple of (object, created), where object is the
created or updated object and created is a boolean specifying
whether a new object was created.
The update_or_create method tries to fetch an object from
database based on the given kwargs. If a match is found, it
updates the fields passed in the defaults dictionary.
"""
if defaults is None:
defaults = {}
key, created = SigningKey.objects.get_or_create(
defaults=defaults,
**kwargs
)
if not created:
for attrib, value in defaults.items():
setattr(key, attrib, value)
key.save()
return key, created
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment