Makes sure all the optional fields are loaded.

If id present (==instance exists in db) fetches data from db.
Defaults are used for new instances.
513257
public function load_optional_fields() {
        global $DB;
        foreach ($this->optional_fields as $field=>$default) {
            if (property_exists($this, $field)) {
                continue;
            }
            if (empty($this->id)) {
                $this->$field = $default;
            } else {
                $this->$field = $DB->get_field($this->table, $field, array('id', $this->id));
            }
        }
    }
1047697
public function requireDefaultRecords()
    {
        parent::requireDefaultRecords();

        $pendingJobs = QueuedJobDescriptor::get()->filter([
            'Implementation' => CheckForUpdatesJob::class,
            'JobStatus' => [
                QueuedJob::STATUS_NEW,
                QueuedJob::STATUS_INIT,
                QueuedJob::STATUS_RUN,
            ],
        ]);
        if ($pendingJobs->count()) {
            return;
        }

        /** @var QueuedJobService $jobService */
        $jobService = QueuedJobService::singleton();
        $jobService->queueJob(Injector::inst()->create(CheckForUpdatesJob::class));
    }
1192098
public function requireDefaultRecords()
    {
        // Require Default Records (from parent):
        
        parent::requireDefaultRecords();
        
        // Create Default Folders:
        
        Folder::singleton()->createDefaultFolders();
        
        // Obtain App Instance:
        
        $app = self::instance();
        
        // Load Defaults:
        
        $app->loadDefaults();
        
        // Load Fixtures:
        
        $app->loadFixtures();
    }
212526
def _init_values(self, context=None):
        
        if context is None:
            context = self.env.context
        # Get basic fields (no relational ones)
        basic_fields = []
        for field_name in self._columns:
            field = self._columns[field_name]
            if not getattr(field, 'relation', False):
                basic_fields.append(field_name)
        # Fetch values from the server
        if self.ids:
            rows = self.__class__.read(
                self.ids, basic_fields, context=context, load='_classic_write')
            ids_fetched = set()
            for row in rows:
                ids_fetched.add(row['id'])
                for field_name in row:
                    if field_name == 'id':
                        continue
                    self._values[field_name][row['id']] = row[field_name]
            ids_in_error = set(self.ids) - ids_fetched
            if ids_in_error:
                raise ValueError(
                    "There is no '{model}' record with IDs {ids}.".format(
                        model=self._name, ids=list(ids_in_error)))
        # No ID: fields filled with default values
        else:
            default_get = self.__class__.default_get(
                list(self._columns), context=context)
            for field_name in self._columns:
                self._values[field_name][None] = default_get.get(
                    field_name, False)
489303
public function requireDefaultRecords()
    {
        if (!$this->supportsElemental()) {
            return;
        }

        $ownerClass = get_class($this->owner);
        $elementalAreas = $this->owner->getElementalRelations();
        $schema = $this->owner->getSchema();

        // There is no inbuilt filter for null values
        $where = [];
        foreach ($elementalAreas as $areaName) {
            $queryDetails = $schema->sqlColumnForField($ownerClass, $areaName . 'ID');
            $where[] = $queryDetails . ' IS NULL OR ' . $queryDetails . ' = 0' ;
        }

        foreach ($ownerClass::get()->where(implode(' OR ', $where)) as $elementalObject) {
            $elementalObject->ensureElementalAreasExist($elementalAreas)->write();
        }
    }
473389
function (id, options, cb) {
    if (arguments.length !== 3) {
      cb = options;
      options = {};
    }
    var self = this;
    var model = this.get(id);
    if (model){
      return cb(null, model);
    }
    function done() {
      var model = self.get(id);
      if (model) {
        if (cb){
          cb(null, model);
        }
      } else {
        cb(new Error('not found'));
      }
    }
    if (options.all) {
      this.fetch({
        callback: done
      });
    } else {
      this.fetchById(id, cb);
    }
  }
22218
def load(self, id=None):
        """"""
        if id is not None:
            # We are asked to change our ID to something else
            self.reset()
            self._setID(id)
        if not self._new and self._validID():
            self._loadDB()
        self._updated = time.time()
187735
public void init() {
        if (FacesContext.getCurrentInstance().getPartialViewContext().isAjaxRequest()) {
            return;
        }

        if (id != null && !"".equals(id)) {
            entity = crudService.findById(id);
            if (entity == null) {
                log.info(String.format("Entity not found with id %s, a new one will be initialized.", id));
                id = null;
                entity = initEntity();
            }
        }
    }
1013484
def field_exists(app_name, model_name, field_name):
    
    model = apps.get_model(app_name, model_name)
    table_name = model._meta.db_table
    cursor = connection.cursor()
    field_info = connection.introspection.get_table_description(cursor, table_name)
    field_names = [f.name for f in field_info]
    return field_name in field_names
506773
def fetch
      instance = id ? find(id, computed_scope) : build(build_params, computed_scope)
      decorate(instance)
    end
690206
def reload
      object = self.id.present? ? 
                 persistence_class.where(id: self.id).first_or_initialize : 
                 self

      serialize! object.attributes
    end
1011167
def get(cls, database, conditions=""):
        
        assert isinstance(database, Database), "database must be database.Database class instance"
        assert isinstance(conditions, string_types), "conditions must be a string"
        if conditions:
            conditions += " AND"
        field_names = ','.join(cls.fields())
        return database.select("SELECT %s FROM %s WHERE %s database='%s'" %
                               (field_names,  cls.table_name(), conditions, database.db_name), model_class=cls)
295017
def _model_exists_step(self, model, should_exist):
    

    model = get_model(model)
    data = guess_types(self.hashes)

    queryset = model.objects

    try:
        existence_check = _TEST_MODEL[model]
    except KeyError:
        existence_check = test_existence

    failed = 0
    try:
        for hash_ in data:
            match = existence_check(queryset, hash_)

            if should_exist:
                assert match, \
                    "%s does not exist: %s" % (model.__name__, hash_)
            else:
                assert not match, \
                    "%s exists: %s" % (model.__name__, hash_)

    except AssertionError as exc:
        print(exc)
        failed += 1

    if failed:
        print("Rows in DB are:")
        for existing_model in queryset.all():
            _dump_model(existing_model,
                        attrs=[k[1:]
                               for k in data[0].keys()
                               if k.startswith('@')])

        if should_exist:
            raise AssertionError("%i rows missing" % failed)
        else:
            raise AssertionError("%i rows found" % failed)
1048797
def fetch_object_from_db_by_pk(self,
                                   obj: Any,
                                   table: str,
                                   fieldlist: Sequence[str],
                                   pkvalue: Any) -> bool:
        """"""
        if pkvalue is None:
            blank_object(obj, fieldlist)
            return False
        row = self.fetchone(
            get_sql_select_all_non_pk_fields_by_pk(table, fieldlist,
                                                   self.get_delims()),
            pkvalue
        )
        if row is None:
            blank_object(obj, fieldlist)
            return False
        setattr(obj, fieldlist[0], pkvalue)  # set PK value of obj
        assign_from_list(obj, fieldlist[1:], row)  # set non-PK values of obj
        return True
1330105
def all_optional_fields(self):
        
        def optional_check(f):
            return is_nullable_type(f.data_type) or f.has_default
        return self._filter_fields(optional_check)
56178
function (i) {
                    if (i >= columns.length) {
                        insertIntoDB();
                        return;
                    }

                    var dbField = columns[i];
                    var field = dbField.Field;

                    //Check required fields
                    if (dbField.Null === 'NO' && 
                        dbField.Default === '' && 
                        dbField.Extra !== 'auto_increment' && 
                        dbField.Extra.search('on update')===-1) {

                        //Check if field not set
                        if (undefOrEmpty(req.body[field])) {
                            return sendError(res,"Field " + field + " is NOT NULL but not specified in this request");
                        } else {
                            //Check if the set values are roughly okay
                            value = checkIfSentvaluesAreSufficient(req,dbField);
                            console.log(value);
                            if(value !== false) {
                                //Value seems okay, go to the next field
                                insertJson[field] = value;
                                iterator(i + 1);
                            } else {
                                return sendError(res,'Value for field ' + field + ' is not sufficient. Expecting ' + dbField.Type + ' but got ' + typeof req.body[field] );
                            }
                        }
                    }  else {
                        //Check for not required fields
                        //Skip auto_incremented fields
                        if(dbField.Extra === 'auto_increment') {
                            iterator(i + 1);
                        } else {
                            //Check if the field was provided by the client
                            var defined = false;
                            if(dbField.Default == "FILE") {
                                if(req.files.hasOwnProperty(dbField.Field)) {
                                    defined = true;
                                }
                            } else {
                                if(typeof req.body[field] !== "undefined") {
                                    defined = true;
                                }
                            }

                            //If it was provided, check if the values are okay
                            if(defined) {
                                value = checkIfSentvaluesAreSufficient(req,dbField);
                                if(value !== false) {
                                    insertJson[field] = value;
                                    iterator(i + 1);
                                } else {
                                    if(dbField.Default == "FILE") {
                                        return sendError(res, 'Value for field ' + field + ' is not sufficient. Either the file is to large or an other error occured');
                                    } else {
                                        return sendError(res, 'Value for field ' + field + ' is not sufficient. Expecting ' + dbField.Type + ' but got ' + typeof req.body[field]);
                                    }
                                }
                            } else {
                                //If not, don't mind
                                iterator(i + 1);
                            }

                        }
                    }

                }
437524
def update(instance, full_clean=True, post_save=False, **kwargs):
    ""

    # apply the updated args to the instance to mimic the change
    # note that these might slightly differ from the true database values
    # as the DB could have been updated by another thread. callers should
    # retrieve a new copy of the object if up-to-date values are required
    for k, v in kwargs.iteritems():
        if isinstance(v, ExpressionNode):
            v = resolve_expression_node(instance, v)
        setattr(instance, k, v)

    # clean instance before update
    if full_clean:
        instance.full_clean()

    # fields that use auto_now=True should be updated corrected, too!
    for field in instance._meta.fields:
        if hasattr(field, 'auto_now') and field.auto_now and field.name not in kwargs:
            kwargs[field.name] = field.pre_save(instance, False)

    rows_affected = instance.__class__._default_manager.filter(
        pk=instance.pk).update(**kwargs)

    if post_save:
        signals.post_save.send(sender=instance.__class__, instance=instance)

    return rows_affected