Last active
August 29, 2015 14:20
-
-
Save miratcan/d19c0616dd0e31d08645 to your computer and use it in GitHub Desktop.
When you need to create a record of a model and delete duplicates same time you can use this method.
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
def create_and_delete_others(cls, **kwargs): | |
""" | |
1. Get first record of model cls from db with given kwargs. | |
2. If found, update that record with update_params. | |
2. If not found, create instance with create_params. | |
3. If more than one found, delete others. | |
""" | |
create_params = kwargs.pop('create_params', {}) | |
update_params = kwargs.pop('update_params', {}) | |
save_params = kwargs.pop('save_params', {}) | |
created = False | |
try: | |
instance = cls.objects.get(**kwargs) | |
except cls.DoesNotExist: | |
created = True | |
instance = cls(**create_params) | |
except cls.MultipleObjectsReturned: | |
instance = cls.objects.filter(**kwargs)[0] | |
# We're deleting redundant instances one by one to call delete | |
# method inside klass. | |
for _i in cls.objects.filter(**kwargs).exclude(instance.id): | |
_i.delete() | |
if update_params: | |
for k, v in update_params.iteritems(): | |
setattr(instance, k, v) | |
instance.save(**save_params) | |
if created: | |
logger.info('Created %s with: %s, called save with params: %s' \ | |
% (cls.__name__, create_params, save_params)) | |
else: | |
logger.info('Found %s with: %s, called save with params: %s' % \ | |
(cls.__name__, kwargs, save_params)) | |
return created, instance |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment