Last active
August 29, 2015 14:06
-
-
Save jorgenschaefer/33495c490724a12f1c49 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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