Find related object on the database and updates it with attributes in self, if it didn't
 find it on database it creates a new one.
168
def convert(attribute="id")
        klass = persistence_class
        object = klass.where(attribute.to_sym => self.send(attribute)).first

        object ||= persistence_class.new

        attributes = self.attributes.select{ |key, value| self.class.serialized_attributes.include?(key.to_s) }

        attributes.delete(:id)

        object.attributes = attributes

        object.save

        self.id = object.id

        object
      end
23189
def find_or_new(self, id, columns=None):
        
        if columns is None:
            columns = ['*']

        instance = self.find(id, columns)

        if instance is None:
            instance = self._related.new_instance()
            self._set_foreign_attributes_for_create(instance)

        return instance
1184054
async def save(self):
        

        if hasattr(self, "before_save"):
            self.before_save()

        query = r.table(self.table_name)

        if self._state.get("id"):
            query = query \
                .get(self._state.get("id")) \
                .update(self.__db_repr, return_changes=True)
        else:
            query = query \
                .insert(self.__db_repr, return_changes=True)

        resp = await query.run(await conn.get())

        try:
            changes = resp["changes"]

            if len(changes) > 0:
                self.wrap(resp["changes"][0]["new_val"])
        except KeyError:
            raise UnexpectedDbResponse()

        if resp["skipped"] > 0:
            raise UnexpectedDbResponse(
                "Model with id `%s` not found in the database." %
                self._state.get("id"))

        return self
831830
def save(self, obj):
        
        session = self.get_db_session()
        session.add(obj)
        session.commit()

        return obj
1030254
def refresh_model(self, model, *, overwrite=False):
    
    new_model = self.find_model_by_id(model.__class__, model.primary_key)
    if overwrite:
      model.update(new_model.to_dict(use_default_excludes=False))
      return model
    else:
      return new_model
958482
def find_or_new(self, id, columns=None):
        
        instance = self._query.find(id, columns)
        if instance is None:
            instance = self.get_related().new_instance()

        return instance
887676
function(instance, relatedObject, options) {
    var opts = _.defaults({}, options, { follow: true, attrs: true });
    var inverse = opts.follow && relatedObject &&
      relatedObject[this.inverse + 'Relation'];

    if (opts.attrs) {
      // set the foreign key property as well
      instance.setAttribute(this.foreignKeyAttr,
        relatedObject[this.primaryKey]);
    }

    this._setRelated(instance, relatedObject);

    if (inverse) {
      inverse.associate(relatedObject, instance, _.extend({}, options, {
        follow: false,
      }));
    }
  }
1224663
def delete(self):
        
        del_query = self._clone()

        # The delete is actually 2 queries - one to find related objects,
        # and one to delete. Make sure that the discovery of related
        # objects is performed on the same database as the deletion.
        del_query._clear_ordering()
        connection = self.model._meta.dj_connection

        connection.connection.delete_by_query(indices=connection.database, doc_types=self.model._meta.db_table,
                                              query=del_query._build_query())
        connection.connection.indices.refresh(indices=connection.database)
        # Clear the result cache, in case this QuerySet gets reused.
        self._result_cache = None
1284239
def update(self, _attributes=None, **attributes):
        
        if _attributes is not None:
            attributes.update(_attributes)

        instance = self.get_results()

        return instance.fill(attributes).save()
1109659
def update(self, *objs):
        
        keys = self.keys()
        new_keys = get_objs_columns(objs, self.realfieldb)

        modified = False
        for v in new_keys:
            if v in keys:    #the id has been existed, so don't insert new record
                keys.remove(v)
            else:
                d = {self.fielda:self.valuea, self.fieldb:v}
                if self.before_save:
                    self.before_save(d)
                if self.through_model:
                    obj = self.through_model(**d)
                    obj.save()
                else:
                    self.do_(self.table.insert().values(**d))
                modified = True
                
        if keys: #if there are still keys, so delete them
            self.clear(*keys)
            modified = True
        
        #cache [] to _STORED_attr_name
        setattr(self.instance, self.store_key, new_keys)
        
        return modified
1224577
def update(self, attributes=None):
        

        if attributes is None:
            attributes = {}

        headers = self.__class__.create_headers(attributes)
        headers.update(self._update_headers())

        result = self._client._put(
            self._update_url(),
            self.__class__.create_attributes(attributes, self),
            headers=headers
        )

        self._update_from_resource(result)

        return self
1317011
def create(self, _attributes=None, _joining=None, _touch=True, **attributes):
        
        if _attributes is not None:
            attributes.update(_attributes)

        instance = self._related.new_instance(attributes)

        instance.save({"touch": False})

        self.attach(instance.get_key(), _joining, _touch)

        return instance
38284
def update_many(self, **kwargs):
        
        db_objects = self.get_dbcollection_with_es(**kwargs)
        return self.Model._update_many(
            db_objects, self._json_params, self.request)
829537
def related_items_changed(self, instance, related_manager):
        
        try:
            count = related_manager.count_queryset()
        except AttributeError:
            count = related_manager.count()
        count_field_name = list(self.fields.keys())[0] % \
                           self.related_field_name
        setattr(instance, count_field_name, count)
        instance.save()
591841
def update(self, **kwargs):
        
        self.validate(**kwargs)
        for attr, value in kwargs.items():
            setattr(self, attr, value)
        return self
1047127
def update_object_in_db(self,
                            obj: Any,
                            table: str,
                            fieldlist: Sequence[str]) -> None:
        """"""
        self.ensure_db_open()
        pkvalue = getattr(obj, fieldlist[0])
        valuelist = []
        # Non-PK fields first
        for f in fieldlist[1:]:
            valuelist.append(getattr(obj, f))
        # Then PK
        valuelist.append(pkvalue)
        cursor = self.db.cursor()
        self.db_exec_with_cursor(
            cursor,
            get_sql_update_by_first_field(table, fieldlist, self.get_delims()),
            *valuelist
        )
410513
def _attach_to_model(self, model):
        
        super(RelatedFieldMixin, self)._attach_to_model(model)

        if model.abstract:
            # do not manage the relation if it's an abstract model
            return

        # now, check related_name and save the relation in the database

        # get related parameters to identify the relation
        self.related_name = self._get_related_name()
        self.related_to = self._get_related_model_name()

        # create entry for the model in the _relations list of the database
        if not hasattr(self.database, '_relations'):
            self.database._relations = {}
        self.database._relations.setdefault(self.related_to, [])

        # check unicity of related name for related model
        self._assert_relation_does_not_exists()

        # the relation didn't exists, we can save it
        relation = (self._model._name, self.name, self.related_name)
        self.database._relations[self.related_to].append(relation)