Returns field's single value prepared for saving into a database.
19960
def value_to_db(self, value):
        
        if isinstance(value, six.string_types):
            value = value.encode("utf_8")
        return value
445650
def get_db_prep_value(self, value, connection=None, prepared=False):
        
        if not value:
            return
        if prepared:
            return value
        else:
            assert(isinstance(value, list) or isinstance(value, tuple))
            return self.separator.join([unicode(s) for s in value])
475552
private static Object generateValue(Field field) {
    Class<?> rawType = field.getType();

    //TODO Objects other than Lists might need parametrized types.
    if (List.class.isAssignableFrom(rawType)) {
      ParameterizedType genericType = (ParameterizedType) field.getGenericType();
      return createListObject(genericType);
    }

    return generateValue(rawType);
  }
402447
def save_one_data(self, data, table):
        '''
        
        '''
        key_map = {}
        if len(data) == 0:
            print('请确保data被正确传入了')
            return -1
        fields = ''
        values = ''
        datas = {}
        for k, v in data.items():
            # 防止sql注入
            datas.update({k: pymysql.escape_string(str(v))})
        for d in datas:
            fields += "`{}`,".format(str(d))
            values += "'{}',".format(str(datas[d]))
        if len(fields) <= 0 or len(values) <= 0:
            return -1
        # 生成sql语句
        sql = "insert ignore into {}({}) values({})".format(
            table, fields[:-1], values[:-1])
        res = self.query(sql)
        return 1 if res != -1 else res
1273966
public function save(): int
    {
        $data = $this->getData();
        $originalData = (array)$this->originalData;
        $toUpdate = [];

        if (count($originalData) == 0) {
            // there's nothing in original data, means we need to insert this
            $toUpdate = $data;
        } else {
            foreach ($data as $field => $value) {
                if (array_key_exists($field, $originalData)) {
                    $doUpdate = false;

                    if ($value !== $originalData[$field]) {
                        // might need to update
                        if (is_scalar($value) && is_scalar($originalData[$field])) {
                            if ((string)$value !== (string)$originalData[$field]) {
                                $doUpdate = true;
                            }
                        } else {
                            $doUpdate = true;
                        }
                    }

                    if ($doUpdate) {
                        $toUpdate[$field] = $value;
                    }
                } else {
                    $toUpdate[$field] = $value;
                }
            }
        }

        if (count($toUpdate) > 0) {
            // we know we have something to update now

            if (!is_array(static::$primaryKey)) {
                if (isset($originalData[static::$primaryKey])) {
                    // we have pk value, so lets update
                    $update = new Update(static::getTableName(), $toUpdate, static::getAdapterConnection());

                    if (!is_array(static::$primaryKey)) {
                        $update->where(static::$primaryKey, $data[static::$primaryKey]);
                    } else {
                        foreach (static::$primaryKey as $field) {
                            $update->where($field, $data[$field]);
                        }
                    }

                    $result = $update->exec()->rowCount();
                    $this->originalData = $this->data;

                    return $result;
                } else {
                    // we don't have pk value, so lets insert
                    $insert = new Insert(static::getTableName(), $toUpdate, static::getAdapterConnection());
                    $insert->exec();
                    $this->data[static::$primaryKey] = Db::getAdapter(static::getAdapterConnection())
                      ->getLastInsertId();
                    $this->originalData = $this->data;
                    return 0;
                }
            } else {
                $update = new Update(static::getTableName(), null, static::getAdapterConnection());

                foreach (static::$primaryKey as $field) {
                    if (!$this->has($field)) {
                        throw new Exception('Can not execute save() method when primary key fields are not present in ' . get_class($this));
                    }

                    $update->where($field, $this->$field);

                    if (array_key_exists($field, $toUpdate)) {
                        unset($toUpdate[$field]);
                    }
                }

                $update->setValues($toUpdate);
                $result = $update->exec()->rowCount();
                $this->originalData = $this->data;

                return $result;
            }

        }

        return -1;
    }
286544
def _get_prepped_model_field(model_obj, field):
    

    # Get the field
    field = model_obj._meta.get_field(field)

    # Get the value
    value = field.get_db_prep_save(getattr(model_obj, field.attname), connection)

    # Return the value
    return value
273969
def pre_save(self, instance, add):
        """"""
        slug = self.value_from_object(instance)

        # We don't want to change slug defined by user.
        predefined_slug = bool(slug)

        if not slug and self.populate_from:
            slug = self._get_populate_from_value(instance)

        if slug:
            slug = slugify(slug)

        if not slug:
            slug = None

            if not self.blank:
                slug = instance._meta.model_name  # pylint: disable=protected-access
            elif not self.null:
                slug = ''

        if slug:
            # Make sure that auto generated slug with added sequence
            # won't excede maximal length.
            # Validation of predefined slugs is handled by Django.
            if not predefined_slug:
                slug = slug[:(self.max_length - MAX_SLUG_SEQUENCE_DIGITS - 1)]

            constraints_placeholder, constraints_values = self._get_unique_constraints(instance)

            instance_pk_name = instance._meta.pk.name  # pylint: disable=protected-access

            # Safe values - make sure that there is no chance of SQL injection.
            query_params = {
                'constraints_placeholder': constraints_placeholder,
                'slug_column': connection.ops.quote_name(self.column),
                'slug_len': len(slug),
                'table_name': connection.ops.quote_name(self.model._meta.db_table),  # pylint: disable=protected-access
                'pk_neq_placeholder': 'AND {} != %(instance_pk)s'.format(instance_pk_name) if instance.pk else ''
            }

            # SQL injection unsafe values - will be escaped.
            # Keys prefixed with `unique_` are reserved for `constraints_values` dict.
            query_escape_params = {
                'slug': slug,
                'slug_regex': '^{}(-[0-9]*)?$'.format(slug),
            }
            query_escape_params.update(constraints_values)
            if instance.pk:
                query_escape_params['instance_pk'] = instance.pk

            with connection.cursor() as cursor:
                # TODO: Slowest part of this query is `MAX` function. It can
                #       be optimized by indexing slug column by slug sequence.
                #       https://www.postgresql.org/docs/9.4/static/indexes-expressional.html
                cursor.execute(
                    """
                    SELECT
                        CASE
                            WHEN (
                                EXISTS(
                                    SELECT 1 FROM {table_name} WHERE (
                                        {slug_column} = %(slug)s
                                        {pk_neq_placeholder}
                                        {constraints_placeholder}
                                    )
                                )
                            ) THEN MAX(slug_sequence) + 1
                            ELSE NULL
                        END
                    FROM (
                        SELECT COALESCE(
                            NULLIF(
                                RIGHT({slug_column}, -{slug_len}-1),
                                ''
                            ),
                            '1'
                        )::text::integer AS slug_sequence
                        FROM {table_name} WHERE (
                            {slug_column} ~ %(slug_regex)s
                            {pk_neq_placeholder}
                            {constraints_placeholder}
                        )
                    ) AS tmp
                    """.format(**query_params),
                    params=query_escape_params
                )
                result = cursor.fetchone()[0]

            if result is not None:
                if predefined_slug:
                    raise SlugError(
                        "Slug '{}' (version {}) is already taken.".format(slug, instance.version)
                    )

                if len(str(result)) > MAX_SLUG_SEQUENCE_DIGITS:
                    raise SlugError(
                        "Auto-generated slug sequence too long - please choose a different slug."
                    )

                slug = '{}-{}'.format(slug, result)

            # Make the updated slug available as instance attribute.
            setattr(instance, self.name, slug)

        return slug
776218
def to_internal_value(self, data):
        """"""
        if self.kwargs['many']:
            serializer = self.serializer.child
            if not isinstance(data, list):
                raise ParseError("'%s' value must be a list" % self.field_name)
            return [
                self.to_internal_value_single(
                    instance,
                    serializer
                ) for instance in data
            ]
        return self.to_internal_value_single(data, self.serializer)
839375
public int getRawFieldData(Convert field)
    {
        if (this.getKey() == null)
            this.setKey(field.getFieldName());
        Object objValue = this.get();
        if ((objValue == null) || (objValue.getClass() == field.getField().getDataClass()))
            return field.setData(objValue); // Should call here
        else
            return field.setString(this.getString());
    }
60786
private Object getFieldValueViaCQL(Object thriftColumnValue, Attribute attribute)
    {
        PropertyAccessor<?> accessor = PropertyAccessorFactory.getPropertyAccessor((Field) attribute.getJavaMember());
        Object objValue;
        try
        {
            if (CassandraDataTranslator.isCassandraDataTypeClass(((AbstractAttribute) attribute).getBindableJavaType()))
            {
                objValue = CassandraDataTranslator.decompose(((AbstractAttribute) attribute).getBindableJavaType(),
                        thriftColumnValue, true);
                return objValue;
            }
            else
            {
                objValue = accessor.fromBytes(((AbstractAttribute) attribute).getBindableJavaType(),
                        (byte[]) thriftColumnValue);
                return objValue;
            }
        }
        catch (PropertyAccessException pae)
        {
            log.warn("Error while setting field{} value via CQL, Caused by: .", attribute.getName(), pae);
        }
        return null;
    }
756137
def pre_save(self, model_instance, add):
        """"""
        value = super().pre_save(model_instance, add)
        if isinstance(value, LocalizedValue):
            for file in value.__dict__.values():
                if file and not file._committed:
                    file.save(file.name, file, save=False)
        return value
904742
def get_default_value(self, field, context, arnum):
        
        name = field.getName()
        default = field.getDefault(context)
        if name == "Batch":
            batch = self.get_batch()
            if batch is not None:
                default = batch
        if name == "Client":
            client = self.get_client()
            if client is not None:
                default = client
        # only set default contact for first column
        if name == "Contact" and arnum == 0:
            contact = self.get_default_contact()
            if contact is not None:
                default = contact
        if name == "Sample":
            sample = self.get_sample()
            if sample is not None:
                default = sample
        # Querying for adapters to get default values from add-ons':
        # We don't know which fields the form will render since
        # some of them may come from add-ons. In order to obtain the default
        # value for those fields we take advantage of adapters. Adapters
        # registration should have the following format:
        # < adapter
        #   factory = ...
        #   for = "*"
        #   provides = "bika.lims.interfaces.IGetDefaultFieldValueARAddHook"
        #   name = "<fieldName>_default_value_hook"
        # / >
        hook_name = name + '_default_value_hook'
        adapter = queryAdapter(
            self.request,
            name=hook_name,
            interface=IGetDefaultFieldValueARAddHook)
        if adapter is not None:
            default = adapter(self.context)
        logger.info("get_default_value: context={} field={} value={} arnum={}"
                    .format(context, name, default, arnum))
        return default
321617
def convert_to_database_compatible_value(value):
    
    if pd.isnull(value):
        return None
    if isinstance(value, pd.Timestamp):
        return value.to_pydatetime()
    try:
        return value.item()
    except AttributeError:
        return value
1197551
def to_internal_value_single(self, data, serializer):
        """"""
        related_model = serializer.Meta.model
        if isinstance(data, related_model):
            return data
        try:
            instance = related_model.objects.get(pk=data)
        except related_model.DoesNotExist:
            raise ValidationError(
                "Invalid value for '%s': %s object with ID=%s not found" %
                (self.field_name, related_model.__name__, data)
            )
        return instance
1088592
def get_db_prep_value(self, value, connection, prepared=False):
        
        if prepared:
            return value

        if value is None:
            return []

        values = value if self.multi_valued_field else [value]
        prepared_values = [self.get_prep_value(v) for v in values]

        # Remove duplicates.
        # https://tools.ietf.org/html/rfc4511#section-4.1.7 :
        # "The set of attribute values is unordered."
        # We keep those values sorted in natural order to avoid useless
        # updates to the LDAP server.
        return list(sorted(set(v for v in prepared_values if v)))
1087878
def get_field_value(self, name):
        
        name = self.get_real_name(name)

        if not name or name in self.__deleted_fields__:
            return None
        modified = self.__modified_data__.get(name)
        if modified is not None:
            return modified
        return self.__original_data__.get(name)
939482
function getone($field = '')
    {
        $this->limit('1');
        if ($this->auto_cache or !empty($cache_id))
        {
            $cache_key = empty($cache_id) ? self::CACHE_PREFIX . '_one_' . md5($this->sql) : self::CACHE_PREFIX . '_all_' . $cache_id;
            global $php;
            $record = $php->cache->get($cache_key);
            if (empty($data))
            {
                if ($this->is_execute == 0)
                {
                    $this->exeucte();
                }
                $record = $this->result->fetch();
                $php->cache->set($cache_key, $record, $this->cache_life);
            }
        }
        else
        {
            if ($this->is_execute == 0)
            {
                $this->exeucte();
            }
            $record = $this->result->fetch();
        }
        if ($field === '')
        {
            return $record;
        }
        return $record[$field];
    }