Skip to content

Instantly share code, notes, and snippets.

@miratcan
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miratcan/d19c0616dd0e31d08645 to your computer and use it in GitHub Desktop.
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.
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