Save model into database and try to load it back as a new model of specified class.
Instance of new class is returned.
776019
public function saveAs($model)
    {
        if (is_string($model)) {
            $model = $this->app->normalizeClassName($model, 'Model');
            $model = $this->add($model);
        }
        $this->_save_as = $model;
        $res = $this->save();
        $this->_save_as = null;

        return $res;
    }
394771
async def add(self, *instances, using_db=None) -> None:
        
        if not instances:
            return
        if self.instance.id is None:
            raise OperationalError(
                "You should first call .save() on {model}".format(model=self.instance)
            )
        db = using_db if using_db else self.model._meta.db
        through_table = Table(self.field.through)
        select_query = (
            db.query_class.from_(through_table)
            .where(getattr(through_table, self.field.backward_key) == self.instance.id)
            .select(self.field.backward_key, self.field.forward_key)
        )
        query = db.query_class.into(through_table).columns(
            getattr(through_table, self.field.forward_key),
            getattr(through_table, self.field.backward_key),
        )

        if len(instances) == 1:
            criterion = getattr(through_table, self.field.forward_key) == instances[0].id
        else:
            criterion = getattr(through_table, self.field.forward_key).isin(
                [i.id for i in instances]
            )

        select_query = select_query.where(criterion)

        already_existing_relations_raw = await db.execute_query(str(select_query))
        already_existing_relations = {
            (r[self.field.backward_key], r[self.field.forward_key])
            for r in already_existing_relations_raw
        }

        insert_is_required = False
        for instance_to_add in instances:
            if instance_to_add.id is None:
                raise OperationalError(
                    "You should first call .save() on {model}".format(model=instance_to_add)
                )
            if (self.instance.id, instance_to_add.id) in already_existing_relations:
                continue
            query = query.insert(instance_to_add.id, self.instance.id)
            insert_is_required = True
        if insert_is_required:
            await db.execute_query(str(query))
1315057
def create(cls, *args, **kwargs) -> 'Entity':
        
        logger.debug(
            f'Creating new `{cls.__name__}` object using data {kwargs}')

        model_cls = repo_factory.get_model(cls)
        repository = repo_factory.get_repository(cls)

        try:
            # Build the entity from the input arguments
            # Raises validation errors, if any, at this point
            entity = cls(*args, **kwargs)

            # Do unique checks, create this object and return it
            entity._validate_unique()

            # Perform Pre-Save Actions
            entity.pre_save()

            # Build the model object and create it
            model_obj = repository.create(model_cls.from_entity(entity))

            # Update the auto fields of the entity
            for field_name, field_obj in entity.meta_.declared_fields.items():
                if isinstance(field_obj, Auto):
                    if isinstance(model_obj, dict):
                        field_val = model_obj[field_name]
                    else:
                        field_val = getattr(model_obj, field_name)
                    setattr(entity, field_name, field_val)

            # Set Entity status to saved
            entity.state_.mark_saved()

            # Perform Post-Save Actions
            entity.post_save()

            return entity
        except ValidationError:
            # FIXME Log Exception
            raise
640909
def get_model(self, model, model_id):
        
        return self._store.find_record(self._get_model_class(model), int(model_id))
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)
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)
489841
def create_model_class(cls, name, table_name, attrs, validations=None, *, otherattrs=None,
                         other_bases=None):
    """"""
    members = dict(table_name=table_name, attrs=attrs, validations=validations or [])
    if otherattrs:
      members.update(otherattrs)
    return type(name, other_bases or (), members)
1050619
def reload(self):
        
        new_model = self.collection.get(self.id)
        self.attrs = new_model.attrs
964996
def create(self, **kwargs):
        
        obj = self.resource(**kwargs)
        obj.save(force_insert=True)
        return obj
1182255
def instance(cls, name):
        
        if not cls._instance.get(name):
            model_name = name.split('.')
            ins_name = '.'.join(
                ['models', model_name[0], 'model', model_name[1]])
            cls._instance[name] = cls.import_model(ins_name)()

        return cls._instance[name]
1296364
def load_data(self, model_instance, *args, **kwargs):
        
        model_dict = copy_model_instance(model_instance)
        return super(DjangoModelReader, self).load_data(**model_dict)
1064019
def _get_model_instance(model_cls, data):
        
        if not isinstance(data, (model_cls, dict)):
            raise TypeError('{0} is not valid type, instance of '
                            '{1} or dict required'.format(data, model_cls))
        return model_cls(**data) if isinstance(data, dict) else data
835112
def create(cls, **kw):
        
        for k, v in kw.items():
            attr = getattr(cls, k, None)
            if isinstance(attr, RecordAttribute):
                kw.pop(k)
                kw.update(attr._decompose(v))
        return cls(**kw)
942311
def fetch_object(self, model_id):
        """"""
        pk_field_instance = getattr(self.object_class, self.pk_field)
        qs = self.object_class.query.filter(pk_field_instance == model_id)
        model = qs.one_or_none()
        if not model:
            raise ReferenceNotFoundError
        return model
815685
def save(self, model):
        
        model.set_attribute(self.get_plain_foreign_key(), self.get_parent_key())

        if model.save():
            return model

        return False
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)
1264637
public function loadModel()
    {
        $modelClassName = $this->namespace . 'Models\Base';

        if (class_exists($modelClassName)) {
            models()->load($modelClassName, strtolower($this->type));
        }
    }