Transform to a MongoDB-safe value.
764828
def to_foreign(self, obj, name, value):
		""""""
		
		if isinstance(value, Iterable) and not isinstance(value, Mapping):
			return self.List(super(Array, self).to_foreign(obj, name, i) for i in value)
		
		return super(Array, self).to_foreign(obj, name, value)
256766
def db_value(self, value):
        """"""
        if isinstance(value, string_types):
            value = arrow.get(value)

        if isinstance(value, arrow.Arrow):
            value = value.datetime

        return super(ArrowDateTimeField, self).db_value(value)
150362
def to_internal_value(self, value):
        """"""
        if value == "":
            return None

        if isinstance(value, string_types):
            slug = slugify(value)
            feature_type, created = FeatureType.objects.get_or_create(
                slug=slug,
                defaults={"name": value}
            )
        else:
            if "id" in value:
                feature_type = FeatureType.objects.get(id=value["id"])
            elif "slug" in value:
                feature_type = FeatureType.objects.get(slug=value["slug"])
            else:
                raise ValidationError("Invalid feature type data")
        return feature_type
882869
def write(self, value):
        
        self.get_collection().update_one(
            {'_id': self._document_id},
            {'$set': {self._path: value}},
            upsert=True
        )
1210659
def to_internal_value(self, value):
        """"""
        natural_key = value.split("_")
        content_type = ContentType.objects.get_by_natural_key(*natural_key)
        return content_type.id
1137214
def transform_incoming(self, son, collection):
        

        def transform_value(value):
            if isinstance(value, collections.MutableMapping):
                if "_id" in value and "_ns" in value:
                    return DBRef(value["_ns"], transform_value(value["_id"]))
                else:
                    return transform_dict(SON(value))
            elif isinstance(value, list):
                return [transform_value(v) for v in value]
            return value

        def transform_dict(object):
            for (key, value) in object.items():
                object[key] = transform_value(value)
            return object

        return transform_dict(SON(son))
86818
def to_simple(self, value, **options):  # nolint
        "  "

        # (string, unicode)
        if isinstance(value, basestring):
            return smart_unicode(value)

        # (int, long, float, real, complex, decimal)
        if isinstance(value, Number):
            return float(str(value)) if isinstance(value, Decimal) else value

        # (datetime, data, time)
        if isinstance(value, (datetime, date, time)):
            return self.to_simple_datetime(value)

        # (dict, ordereddict, mutable mapping)
        if isinstance(value, collections.MutableMapping):
            return dict(
                (k, self.to_simple(v, **options)) for k, v in value.items())

        # (tuple, list, set, iterators)
        if isinstance(value, collections.Iterable):
            return [self.to_simple(o, **options) for o in value]

        # (None, True, False)
        if value is None or value is True or value is False:
            return value

        if hasattr(value, 'to_simple') and not inspect.isclass(value):
            return self.to_simple(value.to_simple(self), **options)

        if isinstance(value, Model):
            return self.to_simple_model(value, **options)

        return str(value)
794342
def to_value(self, obj, resource, visited=set()):
        """"""

        if id(obj) in visited:
            raise ValueError('Circular reference detected when attempting to serialize object')

        if isinstance(obj, (list, tuple, set)):
            return [self.to_value(x, resource) if hasattr(x, '__dict__') else x for x in obj]
        elif hasattr(obj, '__dict__'):
            attrs = obj.__dict__.copy()
            for key in six.iterkeys(obj.__dict__):
                if key.startswith('_'):
                    del attrs[key]

            return {
                self.reverse_aliases.get(k, k):
                    self.to_value(v, resource) if hasattr(v, '__dict__') or isinstance(v, (list, tuple, set)) else v
                for k, v in six.iteritems(attrs)
            }
        else:
            return obj
668970
def serialize(self, value, primitive=False):
        """"""
        if hasattr(value, 'serialize'):
            # i.e. value is a nested model
            return value.serialize(primitive=primitive)
        else:
            return value
1054898
def convert_field_value(type_, value):
    """"""
    if value == ".":
        return None
    elif type_ in ("Character", "String"):
        if "%" in value:
            for k, v in record.UNESCAPE_MAPPING:
                value = value.replace(k, v)
        return value
    else:
        try:
            return _CONVERTERS[type_](value)
        except ValueError:
            warnings.warn(
                ("{} cannot be converted to {}, keeping as " "string.").format(value, type_),
                CannotConvertValue,
            )
            return value
747622
def validate_value(self, value):
        """"""
        if self.readonly:
            raise ValidationError(self.record, "Cannot set readonly field '{}'".format(self.name))
        if value not in (None, self._unset):
            if self.supported_types and not isinstance(value, tuple(self.supported_types)):
                raise ValidationError(self.record, "Field '{}' expects one of {}, got '{}' instead".format(
                    self.name,
                    ', '.join([repr(t.__name__) for t in self.supported_types]),
                    type(value).__name__)
                )
264060
def _transform_value(value, policy, transform_type):
    '''
    
    '''
    t_kwargs = {}
    if 'Transform' in policy:
        if transform_type in policy['Transform']:
            _policydata = _policy_info()
            if transform_type + 'Args' in policy['Transform']:
                t_kwargs = policy['Transform'][transform_type + 'Args']
            return getattr(_policydata, policy['Transform'][transform_type])(value, **t_kwargs)
        else:
            return value
    else:
        if 'Registry' in policy:
            if value == '(value not set)':
                return 'Not Defined'
        return value
1037971
def to_refs(value):
    """"""
    from mongoframes.frames import Frame, SubFrame

    # Frame
    if isinstance(value, Frame):
        return value._id

    # SubFrame
    elif isinstance(value, SubFrame):
        return to_refs(value._document)

    # Lists
    elif isinstance(value, (list, tuple)):
        return [to_refs(v) for v in value]

    # Dictionaries
    elif isinstance(value, dict):
        return {k: to_refs(v) for k, v in value.items()}

    return value
390935
def _normalize_key(value):
  """"""
  if ndb is not None and isinstance(value, (ndb.Model, ndb.Key)):
    return None
  if getattr(value, "key", None):
    return value.key()
  elif isinstance(value, basestring):
    return datastore.Key(value)
  else:
    return value
321979
def clean(self, value):
        """"""
        if value is None:
            value = self.default

        try:
            value = self.to_python(value)
            self.validate(value)
        except ValidationError as error:
            raise ValidationError("invalid value for {}: {}".format(
                self.name,
                error.args[0]
            ))
        return value
60288
def to_set(self):
        '''
        '''
        if self.closed():
            raise ValueError("Attempt to call to_set() on a closed Queryable.")

        if isinstance(self._iterable, set):
            return self._iterable
        s = set()
        for item in self:
            if item in s:
                raise ValueError("Duplicate item value {0} in sequence "
                    "during to_set()".format(repr(item)))
            s.add(item)
        # Ideally we would close here
        #self.close()
        return s
955833
def insert(key, value):
    
    # Pickle the value.
    value = pickle.dumps(value, protocol=constants.PICKLE_PROTOCOL)
    # Store the value as binary data in a document.
    doc = {
        KEY_FIELD: key,
        VALUE_FIELD: Binary(value)
    }
    # Pickle and store the value with its key. If the key already exists, we
    # don't insert (since the key is a unique index), and we don't care.
    try:
        return collection.insert(doc)
    except pymongo.errors.DuplicateKeyError:
        return None