Instantly share code, notes, and snippets.

@munro /mixin.py Secret
Created Apr 28, 2015

Embed
What would you like to do?
def model_instance_unique_query(obj):
unique_together_list = list(obj._meta.unique_together)
if unique_together_list and isinstance(unique_together_list[0], basestring):
unique_together_list = [unique_together_list]
unique_together_list += [
[x.name] for x in ScraperJob._meta.local_fields if x.unique and x.name != 'id'
]
query = Q()
for unique_together in unique_together_list:
query |= reduce(operator.and_, [
Q(**{field: getattr(obj, field)}) for field in unique_together
])
return query
class DjangoUpsertMixin(object):
def __init__(self, *args, **kwargs):
super(DjangoUpsertMixin, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
try:
obj = self._meta.model.objects.get(model_instance_unique_query(self))
setattr(self, obj._meta.pk.name, getattr(obj, obj._meta.pk.name))
except self.DoesNotExist:
pass
super(self._meta.model, self).save(*args, **kwargs)
class TestModel(models.Model, DjangoUpsertMixin):
name = models.CharField(max_length=255, unique=True)
import django
django.setup()
from scraper.datasource.drugstore.models import TestModel
TestModel(name='hey').save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment