Cast instance of model to python structure.

    :param model: Model to be casted.
    :rtype: ``dict``
765568
def to_struct(model):
    
    model.validate()

    resp = {}
    for _, name, field in model.iterate_with_name():
        value = field.__get__(model)
        if value is None:
            continue

        value = field.to_struct(value)
        resp[name] = value
    return resp
392454
def set_model(self, model):
        
        self._model = model

        self._query.from_(model.get_table())

        return self
53550
def _load_model(self, dct):
        
        classname, version, _ = _pop_metadata(dct)

        _check_version(version)
        cls = self._models[classname]

        # Use `from_json` if available
        if hasattr(cls, 'from_json'):
            return cls.from_json(dct)

        # Default to object constructor
        return cls(**dct)
95561
def to_simple_model(self, instance, **options): # noqa
        
        options = self.init_options(**options)
        fields, include, exclude, related = options['fields'], options['include'], options['exclude'], options['related'] # noqa

        result = dict(
            model=smart_unicode(instance._meta),
            pk=smart_unicode(
                instance._get_pk_val(), strings_only=True),
            fields=dict(),
        )

        default_fields = set([field.name for field in instance._meta.fields if field.serialize])
        serialized_fields = fields or (default_fields | include) - exclude

        for fname in serialized_fields:

            # Respect `to_simple__<fname>`
            to_simple = getattr(
                self.scheme, 'to_simple__{0}'.format(fname), None)

            if to_simple:
                result['fields'][fname] = to_simple(instance, serializer=self)
                continue

            related_options = related.get(fname, dict())
            if related_options:
                related_options = self.init_options(**related_options)

            if fname in default_fields and not related_options:
                field = instance._meta.get_field(fname)
                value = field.value_from_object(instance)

            else:
                value = getattr(instance, fname, None)
                if isinstance(value, Manager):
                    value = value.all()

            result['fields'][fname] = self.to_simple(
                value, **related_options)

        if self.format != 'django':
            fields = result['fields']
            fields['id'] = result['pk']
            result = fields

        return result
835285
def _serialize_model_helper(self, model, field_dict=None):
        
        field_dict = field_dict or self.dot_field_list_to_dict()
        if model is None:
            return None

        if isinstance(model, Query):
            model = model.all()

        if isinstance(model, (list, set)):
            return [self.serialize_model(m, field_dict=field_dict) for m in model]

        model_dict = {}
        for name, sub in six.iteritems(field_dict):
            value = getattr(model, name)
            if sub:
                value = self.serialize_model(value, field_dict=sub)
            model_dict[name] = value
        return model_dict
617242
def model_setattr():
    

    def model_setattr(value, context, **_params):
        setattr(context["model"], context["key"], value)
        return _attr()

    return model_setattr
112087
def parameters_from_model(parameters_model):
        
        parameters = {}
        for p in parameters_model:
            if p.is_function:
                code, defaults, closure = pickle.loads(p.value)
                parameters[p.key] = func_load(code, defaults, closure, globs=globals())
            elif p.is_set:
                parameters[p.key] = set(p.value)
            else:
                parameters[p.key] = p.value
        return parameters
411877
def _from_dict(self, obj_dict):
        
        self._n_folds = obj_dict["param"]["n_folds"]
        self._n_rows = obj_dict["param"]["n_rows"]
        self._use_stored_folds = obj_dict["param"]["use_stored_folds"]

        self._concise_model = Concise.from_dict(obj_dict["init_model"])

        if obj_dict["trained_global_model"] is None:
            self._concise_global_model = None
        else:
            self._concise_global_model = Concise.from_dict(obj_dict["trained_global_model"])

        self._kf = [(fold, np.asarray(train), np.asarray(test)) for fold, train, test in obj_dict["folds"]]
        self._cv_model = {fold: Concise.from_dict(model_dict) for fold, model_dict in obj_dict["output"].items()}
1184208
def _process_model_dict(self, d):
        
        del d['model_type']
        del d['fit_filters']
        del d['predict_filters']

        if d['model_expression'] == self.default_model_expr:
            del d['model_expression']

        if YTRANSFORM_MAPPING[d['ytransform']] == self.default_ytransform:
            del d['ytransform']

        d["name"] = yamlio.to_scalar_safe(d["name"])

        return d
416952
def bind_fields_to_model_cls(cls, model_fields):
        """"""
        return dict(
            (field.name, field.bind_model_cls(cls)) for field in model_fields)
971803
def to_django(self):
        
        exclude = {'name', 'model'}
        field_module = 'models'
        django_kwargs = {}
        if self.node_attrs['model'] == 'CharField':
            django_kwargs['max_length'] = 255
        django_kwargs['blank'] = not self.node_attrs['required']
        try:
            django_kwargs['default'] = self.node_attrs['value']
        except KeyError:
            pass
        return u'{0} = {1}.{2}({3})'.format(self.node_attrs['name'], field_module, self.node_attrs['model'],
                                           ', '.join(['{0}={1}'.format(i,v) for i,v in six.iteritems(django_kwargs)]),)
147954
async def get_model(self, model):
        
        uuids = await self.model_uuids()
        if model in uuids:
            uuid = uuids[model]
        else:
            uuid = model

        from juju.model import Model
        model = Model()
        kwargs = self.connection().connect_params()
        kwargs['uuid'] = uuid
        await model._connect_direct(**kwargs)
        return model
415906
def hashmodel(model, library=None):
    ''''''
    library = library or 'python-stdnet'
    meta = model._meta
    sha = hashlib.sha1(to_bytes('{0}({1})'.format(library, meta)))
    hash = sha.hexdigest()[:8]
    meta.hash = hash
    if hash in _model_dict:
        raise KeyError('Model "{0}" already in hash table.\
 Rename your model or the module containing the model.'.format(meta))
    _model_dict[hash] = model
1284217
def create_model(cls, data: dict, fields=None):
        '''
        
        '''
        if fields is None:
            fields = set(cls._fields.keys())
        else:
            if not isinstance(fields, set):
                fields = set(fields)
        new_keys = set(data.keys()) - fields
        if new_keys:
            for new_key in new_keys:
                del data[new_key]
        return cls(data)
131467
def _dict_to_model(self, data):
        

        try:
            # we can do this because we have same fields
            # in the representation and in the model:
            user = models.User(**data)
        except TypeError:
            # client sent bad data
            raise errors.BadRequest()
        else:
            return user
1356472
def as_dict(self):
        
        result = {}
        for key in self._valid_properties:
            val = getattr(self, key)
            if isinstance(val, datetime):
                val = val.isoformat()
            # Parse custom classes
            elif val and not Model._is_builtin(val):
                val = val.as_dict()
            # Parse lists of objects
            elif isinstance(val, list):
                # We only want to call as_dict in the case where the item
                # isn't a builtin type.
                for i in range(len(val)):
                    if Model._is_builtin(val[i]):
                        continue
                    val[i] = val[i].as_dict()
            # If it's a boolean, add it regardless of the value
            elif isinstance(val, bool):
                result[key] = val

            # Add it if it's not None
            if val:
                result[key] = val
        return result
713866
def _map_dict_keys_to_model_attributes(model_type, model_dict):
    

    new_dict = {}
    for key, value in model_dict.items():
        new_dict[_get_k8s_model_attribute(model_type, key)] = value

    return new_dict