This code must be in its own method since the fetch functions need
        credits to be set. m2m fields are not yet set at the end of either the
        save method or post_save signal.
504010
def set_image(self):
        """"""

        if not self.image:
            scrape_image(self)

        # If still no image then use first contributor image
        if not self.image:
            contributors = self.get_primary_contributors()
            if contributors:
                self.image = contributors[0].image
                self.save(set_image=False)

        # If still not image then default
        if not self.image:
            filename = settings.STATIC_ROOT + 'music/images/default.png'
            if os.path.exists(filename):
                image = File(
                    open(filename, 'rb')
                )
                image.name = 'default.png'
                self.image = image
                self.save(set_image=False)
111346
public function attach()
    {
        $this->loadModel('Field.FieldInstances');

        if ($this->request->data()) {
            $handler = $this->request->data('handler');
            $info = fieldsInfo($handler);
            $type = !empty($info['type']) ? $info['type'] : null;
            $data = $this->request->data();
            $data['eav_attribute'] = array_merge([
                'table_alias' => $this->_tableAlias,
                'bundle' => $this->_getBundle(),
                'type' => $type,
            ], (array)$this->request->data('eav_attribute'));

            $fieldInstance = $this->FieldInstances->newEntity($data, ['associated' => ['EavAttribute']]);
            $this->_validateSlug($fieldInstance);
            $instanceErrors = $fieldInstance->errors();
            $attributeErrors = $fieldInstance->get('eav_attribute')->errors();
            $success = empty($instanceErrors) && empty($attributeErrors);

            if ($success) {
                $success = $this->FieldInstances->save($fieldInstance, ['associated' => ['EavAttribute']]);
                if ($success) {
                    $this->Flash->success(__d('field', 'Field attached!'));
                    $this->redirect($this->referer());
                }
            }

            if (!$success) {
                $this->Flash->danger(__d('field', 'Field could not be attached'));
            }
        } else {
            $fieldInstance = $this->FieldInstances->newEntity();
        }

        $fieldsInfoCollection = fieldsInfo();
        $fieldsList = $fieldsInfoCollection->combine('handler', 'name')->toArray(); // for form select
        $fieldsInfo = $fieldsInfoCollection->toArray(); // for help-blocks

        $this->title(__d('field', 'Attach New Field'));
        $this->set('fieldsList', $fieldsList);
        $this->set('fieldsInfo', $fieldsInfo);
        $this->set('fieldInstance', $fieldInstance);
    }
385969
def contribute_to_class(self, cls, name):
        

        self.update_rel_to(cls)

        # Called to get a name
        self.set_attributes_from_name(name)
        self.model = cls

        # Set the through field
        if not self.remote_field.through and not cls._meta.abstract:
            self.remote_field.through = create_many_to_many_intermediary_model(
                self, cls)

        # Do the rest
        super(M2MFromVersion, self).contribute_to_class(cls, name)
1346945
static void demo(PersistenceManager persistenceManager)
    {

        try {
            // Fetch an account.  Notice that the id is now a long rather than an integer.
            Account account = persistenceManager.findById(Account.class, 1L);
            assert account != null;
            assert account.getAccountId() == 1L;

            // The Account Name is a new field and is now persistable.
            // This demonstrates that we can now take
            // advantage of the new field.
            account.setAccountName("Utility Bill");
            persistenceManager.saveEntity(account);

            // Verify it was indeed persisted
            account = persistenceManager.findById(Account.class, 1L);
            assert account != null;
            assert account.getAccountName().equals("Utility Bill");

            // Notice, the one thing that we cannot demonstrate is that we removed a field, "balanceDue"
            // Don't worry, we can add it back and the data will still be there since it has not been orphaned.
        } catch (OnyxException e)
        {
            e.printStackTrace();
            assert false;
        }
    }
320023
def instantiate(self, params):
        
        try:
            self.send(self.Meta.collection_endpoint, "POST", json=params)
        except CartoRateLimitException as e:
            raise e
        except Exception as e:
            raise CartoException(e)
1106086
def handle_m2m(self, sender, instance, **kwargs):
    
    self.handle_save(instance.__class__, instance)
57453
def raw_field_definition_proxy_post_save(sender, instance, raw, **kwargs):
    
    if raw:
        model_class = instance.content_type.model_class()
        opts = model_class._meta
        if opts.proxy and opts.concrete_model is sender:
            field_definition_post_save(
                sender=model_class, instance=instance.type_cast(), raw=raw,
                **kwargs
            )
1157242
def _fetch(
    queryset, model_objs, unique_fields, update_fields, returning, sync,
    ignore_duplicate_updates=True, return_untouched=False
):
    
    model = queryset.model
    if (return_untouched or sync) and returning is not True:
        returning = set(returning) if returning else set()
        returning.add(model._meta.pk.name)
    upserted = []
    deleted = []
    # We must return untouched rows when doing a sync operation
    return_untouched = True if sync else return_untouched

    if model_objs:
        sql, sql_args = _get_upsert_sql(queryset, model_objs, unique_fields, update_fields, returning,
                                        ignore_duplicate_updates=ignore_duplicate_updates,
                                        return_untouched=return_untouched)

        with connection.cursor() as cursor:
            cursor.execute(sql, sql_args)
            if cursor.description:
                nt_result = namedtuple('Result', [col[0] for col in cursor.description])
                upserted = [nt_result(*row) for row in cursor.fetchall()]

    pk_field = model._meta.pk.name
    if sync:
        orig_ids = queryset.values_list(pk_field, flat=True)
        deleted = set(orig_ids) - {getattr(r, pk_field) for r in upserted}
        model.objects.filter(pk__in=deleted).delete()

    nt_deleted_result = namedtuple('DeletedResult', [model._meta.pk.name, 'status_'])
    return UpsertResult(
        upserted + [nt_deleted_result(**{pk_field: d, 'status_': 'd'}) for d in deleted]
    )
94327
private function bindResultFields()
    {
        $resultMetadata = $this->mysqliStatement->result_metadata();

        if ($resultMetadata !== false) {
            $this->resultFields = array();

            foreach ($resultMetadata->fetch_fields() as $field) {
                $this->resultFields[] = $field->name;
            }

            $resultMetadata->free();
        }
    }
1125261
public function afterFetch()
    {
        $data = (array) $this->data + $this->getDefaultValues();

        /*
         * Repeater form fields store arrays and must be jsonable.
         */
        foreach ($this->getFormFields() as $id => $field) {
            if (!isset($field['type'])) {
                continue;
            }

            if ($field['type'] === 'repeater') {
                $this->jsonable[] = $id;
            }
            elseif ($field['type'] === 'fileupload') {
                $this->attachOne[$id] = File::class;
                unset($data[$id]);
            }
        }

        /*
         * Fill this model with the jsonable attributes kept in 'data'.
         */
        $this->setRawAttributes((array) $this->getAttributes() + $data, true);
    }
965638
static function fetch( $contentAttributeID, $contentObjectVersion, $currencyCode = false, $type = false, $asObjects = true )
    {
        $priceList = null;
        $conds = array();

        $conds['contentobject_attr_id'] = $contentAttributeID;
        $conds['contentobject_attr_version'] = $contentObjectVersion;

        if ( is_array( $currencyCode ) )
            $conds['currency_code'] = array( $currencyCode );
        else if ( $currencyCode != false )
            $conds['currency_code'] = $currencyCode;

        if ( is_array( $type ) )
            $conds['type'] = array( $type );
        else if ( $type != false )
            $conds['type'] = $type;



        $sort = null;
        $limitation = null;

        $rows = eZPersistentObject::fetchObjectList( eZMultiPriceData::definition(),
                                                     null,
                                                     $conds,
                                                     $sort,
                                                     $limitation,
                                                     $asObjects );


        if ( count( $rows ) > 0 )
        {
            $keys = array_keys( $rows );
            foreach ( $keys as $key )
            {
                if ( $asObjects )
                    $priceList[$rows[$key]->attribute( 'currency_code' )] = $rows[$key];
                else
                    $priceList[$rows[$key]['currency_code']] = $rows[$key];
            }
        }

        return $priceList;
    }
1192262
def save(self):
        
        logger.debug(
            f'Saving `{self.__class__.__name__}` object')

        # Fetch Model class and connected repository from Repository Factory
        model_cls = repo_factory.get_model(self.__class__)
        repository = repo_factory.get_repository(self.__class__)

        try:
            # Do unique checks, update the record and return the Entity
            self._validate_unique(create=False)

            # Perform Pre-Save Actions
            self.pre_save()

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

            # Update the auto fields of the entity
            for field_name, field_obj in self.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(self, field_name, field_val)

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

            # Perform Post-Save Actions
            self.post_save()

            return self
        except Exception:
            # FIXME Log Exception
            raise
1192819
def initialize_fields(self):
        
        # # Pull all the "normal" fields off the model instance meta.
        for name, field in self.instance._meta.fields.items():
            if getattr(field, 'primary_key', False):
                continue
            self._meta.fields[name] = self.convert_field(name, field)

        # Many-to-many fields are not stored in the meta fields dict.
        # Pull them directly off the class.
        for name in dir(type(self.instance)):
            field = getattr(type(self.instance), name, None)
            if isinstance(field, ManyToManyField):
                self._meta.fields[name] = self.convert_field(name, field)

        super().initialize_fields()
368865
@Override
  public void saveModel(BackendModel m, String model_path) {
    ((DeepwaterCaffeModel) m).saveModel(model_path);
  }
966688
private function AddSmtpPortField()
    {
        $name = 'SmtpPort';
        $field = Input::Text($name, $this->settings->GetSmtpPort());
        $this->AddField($field);
        $this->AddValidator($name, new Integer(1, 65535));
    }
457820
def initialize_post(self):
        
        self.model = self.get_model()
        for key in self.model.keys():
            self.model.set(key, self.json_arguments.get(key))
1127380
def serialize_m2m_on_save(sender, action, instance, using, **kwargs):
    
    if action == "post_add":
        try:
            wrapped_instance = site_offline_models.get_wrapped_instance(instance)
        except ModelNotRegistered:
            pass
        else:
            wrapped_instance.to_outgoing_transaction(using, created=True)