def _get_queryset_with_instance(self, instance): hints = self._hints if hints: hints['shard_key'] = find_shard_key(instance) else: hints = {'shard_key': find_shard_key(instance)} return self._queryset_class(model=self.model, hints=hints)
def save(self, force_insert=False, force_update=False, using=None, update_fields=None): shard_key = find_shard_key(self) if shard_key is not None: setattr(self, '_shard_key', shard_key) else: raise Exception("Shard Key was none") self.__class__._shards.append(self._shard_key) super(ShardableModel, self).save(force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields)
def db_for_read_or_write(self, model, **hints): # Returns the database based on which database the info # should go to db = 'default' try: instance = hints['instance'] if isinstance(instance, ShardableModel): # check instance chached shard_key (on saves) # before finding it by looping through fields shard_key = getattr(instance, '_shard_key', None) if shard_key is None: shard_key = find_shard_key(instance) db = self.get_database(model, shard_key) print("instance:", instance) print("shard_key:", shard_key) print("db:", db) except KeyError: print("No instance in hints") try: db = self.get_database(model, hints['shard_key']) except KeyError: print("No shard_key in hints") print("Returning", db) return db