Calls the field's ``to_python`` method.
        Override in derived classes of fields which involve models, such as ``ModelField``
434371
async def serialize(self, value, native=False):
        '''
        
        '''
        if native:
            return self.to_python(value)
        return self.to_data(value)
916271
def field_factory(base_class):
    
    from .fields import TranslationField

    class TranslationFieldField(TranslationField, base_class):
        pass

    TranslationFieldField.__name__ = "Translation%s" % base_class.__name__

    return TranslationFieldField
134264
def to_sequence_field(cls):
    
    class SequenceConverter(object):

        def __init__(self, cls):
            self._cls = cls

        @property
        def cls(self):
            return resolve_class(self._cls)

        def __call__(self, values):
            values = values or []
            args = [to_model(self.cls, value) for value in values]
            return TypedSequence(cls=self.cls, args=args)

    return SequenceConverter(cls)
372946
def add_to_class(self, model_class):
        
        model_class._meta.add_field(self)
        setattr(model_class, self.name, _FieldDescriptor(self))
912097
def _create_model_class(self, model):
        
        cls_name = model.replace('.', '_')
        # Hack for Python 2 (no need to do this for Python 3)
        if sys.version_info[0] < 3:
            if isinstance(cls_name, unicode):
                cls_name = cls_name.encode('utf-8')
        # Retrieve server fields info and generate corresponding local fields
        attrs = {
            '_env': self,
            '_odoo': self._odoo,
            '_name': model,
            '_columns': {},
        }
        fields_get = self._odoo.execute(model, 'fields_get')
        for field_name, field_data in fields_get.items():
            if field_name not in FIELDS_RESERVED:
                Field = fields.generate_field(field_name, field_data)
                attrs['_columns'][field_name] = Field
                attrs[field_name] = Field
        # Case where no field 'name' exists, we generate one (which will be
        # in readonly mode) in purpose to be filled with the 'name_get' method
        if 'name' not in attrs['_columns']:
            field_data = {'type': 'text', 'string': 'Name', 'readonly': True}
            Field = fields.generate_field('name', field_data)
            attrs['_columns']['name'] = Field
            attrs['name'] = Field
        return type(cls_name, (Model,), attrs)
1081037
def get_model_custom_fields(self):
        
        return CustomField.objects.filter(
            content_type=ContentType.objects.get_for_model(self))
136860
def _model_class_from_pk(definition_cls, definition_pk):
    
    try:
        return definition_cls.objects.get(pk=definition_pk).model_class()
    except definition_cls.DoesNotExist:
        pass
1118881
def get_method_returning_field_value(self, field_name):
        
        method = getattr(self, field_name, None)
        return method if method and callable(method) else None
1344495
def to_python(self, value, context=None):
        """"""
        value = value.copy()
        res = {}
        errors = []
        for field, schema in self._fields.items():
            name = schema.get_attr('name', field)
            if name in value:
                try:
                    res[field] = schema.to_python(
                        value.pop(name),
                        context=context
                    )
                except exceptions.ValidationErrors as ex:
                    self._update_errors_by_exception(errors, ex, name)
        self._raise_exception_when_errors(errors, value)
        res.update(value)
        return res
1081689
def get_model_field(model, field_name):
    
    meta = model._meta
    try:
        if DJANGO19:
            field = meta.get_field(field_name)
        else:
            field = meta.get_field_by_name(field_name)[0]
        return field
    except:
        if DJANGO19:
            related_objs = (
                f for f in meta.get_fields()
                if (f.one_to_many or f.one_to_one)
                and f.auto_created and not f.concrete
            )
            related_m2m_objs = (
                f for f in meta.get_fields(include_hidden=True)
                if f.many_to_many and f.auto_created
            )
        else:
            related_objs = meta.get_all_related_objects()
            related_m2m_objs = meta.get_all_related_many_to_many_objects()

        related_objects = {
            o.get_accessor_name(): o
            for o in chain(related_objs, related_m2m_objs)
        }
        if field_name in related_objects:
            return related_objects[field_name]
        else:
            # check virtual fields (1.7)
            if hasattr(meta, 'virtual_fields'):
                for field in meta.virtual_fields:
                    if field.name == field_name:
                        return field

            raise AttributeError(
                '%s is not a valid field for %s' % (field_name, model)
            )
1092441
def _add_model_fields_as_params(app, obj, lines):
    
    for field in obj._meta.get_fields():
        try:
            help_text = strip_tags(force_text(field.help_text))
            verbose_name = force_text(field.verbose_name).capitalize()
        except AttributeError:
            # e.g. ManyToOneRel
            continue

        # Add parameter
        if help_text:
            lines.append(u':param %s: %s' % (field.name, help_text))
        else:
            lines.append(u':param %s: %s' % (field.name, verbose_name))

        # Add type
        lines.append(_get_field_type(field))

    if 'sphinx.ext.inheritance_diagram' in app.extensions and \
            'sphinx.ext.graphviz' in app.extensions and \
            not any('inheritance-diagram::' in line for line in lines):
        lines.append('.. inheritance-diagram::')
642237
def to_python(self, value: Optional[str]) -> Optional[Any]:
        
        # https://docs.djangoproject.com/en/1.8/howto/custom-model-fields/
        # log.debug("to_python: {}, {}", value, type(value))
        if isinstance(value, datetime.datetime):
            return value
        if value is None:
            return value
        if value == '':
            return None
        return iso_string_to_python_datetime(value)
403337
def convert_serializer_field(field, is_input=True):
    

    graphql_type = get_graphene_type_from_serializer_field(field)

    args = []
    kwargs = {"description": field.help_text, "required": is_input and field.required}

    # if it is a tuple or a list it means that we are returning
    # the graphql type and the child type
    if isinstance(graphql_type, (list, tuple)):
        kwargs["of_type"] = graphql_type[1]
        graphql_type = graphql_type[0]

    if isinstance(field, serializers.ModelSerializer):
        if is_input:
            graphql_type = convert_serializer_to_input_type(field.__class__)
        else:
            global_registry = get_global_registry()
            field_model = field.Meta.model
            args = [global_registry.get_type_for_model(field_model)]
    elif isinstance(field, serializers.ListSerializer):
        field = field.child
        if is_input:
            kwargs["of_type"] = convert_serializer_to_input_type(field.__class__)
        else:
            del kwargs["of_type"]
            global_registry = get_global_registry()
            field_model = field.Meta.model
            args = [global_registry.get_type_for_model(field_model)]

    return graphql_type(*args, **kwargs)
2173
def import_field(field_classpath):
    
    if '.' in field_classpath:
        fully_qualified = field_classpath
    else:
        fully_qualified = "django.db.models.%s" % field_classpath
    try:
        return import_dotted_path(fully_qualified)
    except ImportError:
        raise ImproperlyConfigured("The EXTRA_MODEL_FIELDS setting contains "
                                   "the field '%s' which could not be "
                                   "imported." % field_classpath)
322889
def copy_fields(self, model):
        
        fields = {}
        for field in self.fields_included(model):
            field = copy.copy(field)
            field.remote_field = copy.copy(field.remote_field)
            if isinstance(field, OrderWrt):
                # OrderWrt is a proxy field, switch to a plain IntegerField
                field.__class__ = models.IntegerField
            if isinstance(field, models.ForeignKey):
                old_field = field
                old_swappable = old_field.swappable
                old_field.swappable = False
                try:
                    _name, _path, args, field_args = old_field.deconstruct()
                finally:
                    old_field.swappable = old_swappable
                if getattr(old_field, "one_to_one", False) or isinstance(
                    old_field, models.OneToOneField
                ):
                    FieldType = models.ForeignKey
                else:
                    FieldType = type(old_field)

                # If field_args['to'] is 'self' then we have a case where the object
                # has a foreign key to itself. If we pass the historical record's
                # field to = 'self', the foreign key will point to an historical
                # record rather than the base record. We can use old_field.model here.
                if field_args.get("to", None) == "self":
                    field_args["to"] = old_field.model

                # Override certain arguments passed when creating the field
                # so that they work for the historical field.
                field_args.update(
                    db_constraint=False,
                    related_name="+",
                    null=True,
                    blank=True,
                    primary_key=False,
                    db_index=True,
                    serialize=True,
                    unique=False,
                    on_delete=models.DO_NOTHING,
                )
                field = FieldType(*args, **field_args)
                field.name = old_field.name
            else:
                transform_field(field)
            fields[field.name] = field
        return fields
974383
def process_models(attrs, base_model_class):
        
        attrs.update(base_model_class._DEFAULT_BASE_FIELDS)
        attrs['_instance_registry'] = set()
        attrs['_is_unpermitted_fields_set'] = False
        attrs['save_meta_data'] = None
        attrs['_pre_save_hook_called'] = False
        attrs['_post_save_hook_called'] = False
        DEFAULT_META = {'bucket_type': settings.DEFAULT_BUCKET_TYPE,
                        'field_permissions': {},
                        'app': 'main',
                        'list_fields': [],
                        'list_filters': [],
                        'search_fields': [],
                        'fake_model': False,
                        }
        if 'Meta' not in attrs:
            attrs['Meta'] = type('Meta', (object,), DEFAULT_META)
        else:
            for k, v in DEFAULT_META.items():
                if k not in attrs['Meta'].__dict__:
                    setattr(attrs['Meta'], k, v)
882613
def model_fields(model, db_session=None, only=None, exclude=None,
                 field_args=None, converter=None, exclude_pk=False,
                 exclude_fk=False):
    
    mapper = model._sa_class_manager.mapper
    converter = converter or _ModelConverter()
    field_args = field_args or {}
    properties = []

    for prop in mapper.iterate_properties:
        if getattr(prop, 'columns', None):
            if exclude_fk and prop.columns[0].foreign_keys:
                continue
            elif exclude_pk and prop.columns[0].primary_key:
                continue

        properties.append((prop.key, prop))

    # the following if condition is modified:
    if only is not None:
        properties = (x for x in properties if x[0] in only)
    elif exclude:
        properties = (x for x in properties if x[0] not in exclude)

    field_dict = {}
    for name, prop in properties:
        field = converter.convert(
            model, mapper, prop,
            field_args.get(name), db_session
        )
        if field is not None:
            field_dict[name] = field

    return field_dict