Created
June 12, 2015 15:38
-
-
Save synotna/eaccd2586f5d3eda0f68 to your computer and use it in GitHub Desktop.
django bulk_update_or_create work in progress
This file contains 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 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