Skip to content

Instantly share code, notes, and snippets.

@synotna
Created June 12, 2015 15:38
Show Gist options
  • Save synotna/eaccd2586f5d3eda0f68 to your computer and use it in GitHub Desktop.
Save synotna/eaccd2586f5d3eda0f68 to your computer and use it in GitHub Desktop.
django bulk_update_or_create work in progress
def bulk_update_or_create(self, channels, *key_fields):
if len(key_fields) == 1:
key_field = key_fields[0]
key_to_object_mapping = {channel[key_field]: channel for channel in channels}
lookup = {'{}__in'.format(key_field): list(key_to_object_mapping)}
existing = self.filter(**lookup)
existing_keys = existing.values_list(key_field, flat=True)
to_create = [self.model(**channel) for channel in channels
if channel[key_field] not in existing_keys]
self.bulk_create(to_create, batch_size=1000)
for key in existing_keys:
lookup = {key_field: key}
self.filter(**lookup).update(**key_to_object_mapping[key])
else:
raise NotImplementedError()
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment