Rename fields inside an attribute table.

    Only since QGIS 2.16.

    :param layer: The vector layer.
    :type layer: QgsVectorLayer

    :param fields_to_copy: Dictionary of fields to copy.
    :type fields_to_copy: dict
321337
def rename_fields(layer, fields_to_copy):
    
    for field in fields_to_copy:
        index = layer.fields().lookupField(field)
        if index != -1:
            layer.startEditing()
            layer.renameAttribute(index, fields_to_copy[field])
            layer.commitChanges()
            LOGGER.info(
                'Renaming field %s to %s' % (field, fields_to_copy[field]))
        else:
            LOGGER.info(
                'Field %s not present in the layer while trying to renaming '
                'it to %s' % (field, fields_to_copy[field]))
267958
def copy_fields(src, to):
    
    args = tuple(getattr(src, field.attname) for field in src._meta.fields)
    return to(*args)
770328
def _transform_field(field):
    """"""
    if isinstance(field, bool):
        return TRUE if field else FALSE
    elif isinstance(field, (list, dict)):
        return json.dumps(field, sort_keys=True, ensure_ascii=False)
    else:
        return field
1067372
def setLayer(self, layer):
        
        if layer == self._layer:
            return False

        self._layer = layer
        self.syncLayerData()

        return True
7689
def column_to_bq_schema(self):
        
        kwargs = {}
        if len(self.fields) > 0:
            fields = [field.column_to_bq_schema() for field in self.fields]
            kwargs = {"fields": fields}

        return google.cloud.bigquery.SchemaField(self.name, self.dtype,
                                                 self.mode, **kwargs)
615432
def copy_from(self, other):
        
        # Need to copy all attributes, fields, relations
        self.__attributes__ = {k: v.copy() for k, v in other.__attributes__.items()}
        self.__fields__ = {k: v.copy() for k, v in other.__fields__.items()}
        self.__relations__ = {k: v.copy() for k, v in other.__relations__.items()}
        self.maps = {k: m.copy() for k, m in other.maps.items()}
        self.dimensions = other.dimensions.copy()
991469
def add_field(self, field):
        
        if not isinstance(field, fields.BaseField):
            raise ValueError('Argument "field" must be an instance of '
                             'BaseField')
        self.fields.add(field.name, field)
322889
def copy_fields(self, model):
        
        fields = {}
        for field in self.fields_included(model):
            field = copy.copy(field)
            field.remote_field = copy.copy(field.remote_field)
            if isinstance(field, OrderWrt):
                # OrderWrt is a proxy field, switch to a plain IntegerField
                field.__class__ = models.IntegerField
            if isinstance(field, models.ForeignKey):
                old_field = field
                old_swappable = old_field.swappable
                old_field.swappable = False
                try:
                    _name, _path, args, field_args = old_field.deconstruct()
                finally:
                    old_field.swappable = old_swappable
                if getattr(old_field, "one_to_one", False) or isinstance(
                    old_field, models.OneToOneField
                ):
                    FieldType = models.ForeignKey
                else:
                    FieldType = type(old_field)

                # If field_args['to'] is 'self' then we have a case where the object
                # has a foreign key to itself. If we pass the historical record's
                # field to = 'self', the foreign key will point to an historical
                # record rather than the base record. We can use old_field.model here.
                if field_args.get("to", None) == "self":
                    field_args["to"] = old_field.model

                # Override certain arguments passed when creating the field
                # so that they work for the historical field.
                field_args.update(
                    db_constraint=False,
                    related_name="+",
                    null=True,
                    blank=True,
                    primary_key=False,
                    db_index=True,
                    serialize=True,
                    unique=False,
                    on_delete=models.DO_NOTHING,
                )
                field = FieldType(*args, **field_args)
                field.name = old_field.name
            else:
                transform_field(field)
            fields[field.name] = field
        return fields
1153450
def rename(self, mapping):
        
        for old_key, new_key in mapping:
            self.dict[new_key] = self.dict[old_key]
            del self.dict[old_key]
375481
def _add_dynamic_field_to_model(cls, field, field_name):
        
        # create the new field
        new_field = field._create_dynamic_version()
        new_field.name = field_name
        new_field._attach_to_model(cls)

        # set it as an attribute on the class, to be reachable
        setattr(cls, "_redis_attr_%s" % field_name, new_field)

        # NOTE: don't add the field to the "_fields" list, to avoid use extra
        #       memory to each future instance that will create a field for each
        #       dynamic one created

        # # add the field to the list to avoid to done all of this again
        # # (_fields is already on this class only, not subclasses)
        # cls._fields.append(field_name)

        # each subclass needs its own copy
        for subclass in cls.__subclasses__():
            subclass._add_dynamic_field_to_model(field, field_name)

        return new_field
1131751
def enumerate_layer_fields(self, layer):
        
        descriptor = self.get_descriptor_for_layer(layer)
        return [field['name'] for field in descriptor['fields']]
1226851
def setField(self, new_value):
        
        self.B = self.B._replace(val=new_value)
264935
def set_layer(self, layer=None, keywords=None):
        
        if self.field_mapping_widget is not None:
            self.field_mapping_widget.setParent(None)
            self.field_mapping_widget.close()
            self.field_mapping_widget.deleteLater()
            self.main_layout.removeWidget(self.field_mapping_widget)
            self.field_mapping_widget = None

        if layer:
            self.layer = layer
        else:
            self.layer = self.layer_combo_box.currentLayer()
        if not self.layer:
            return

        if keywords is not None:
            self.metadata = keywords
        else:
            # Always read from metadata file.
            try:
                self.metadata = self.keyword_io.read_keywords(self.layer)
            except (
                    NoKeywordsFoundError,
                    KeywordNotFoundError,
                    MetadataReadError) as e:
                raise e
        if 'inasafe_default_values' not in self.metadata:
            self.metadata['inasafe_default_values'] = {}
        if 'inasafe_fields' not in self.metadata:
            self.metadata['inasafe_fields'] = {}
        self.field_mapping_widget = FieldMappingWidget(
            parent=self, iface=self.iface)
        self.field_mapping_widget.set_layer(self.layer, self.metadata)
        self.field_mapping_widget.show()
        self.main_layout.addWidget(self.field_mapping_widget)

        # Set header label
        group_names = [
            self.field_mapping_widget.tabText(i) for i in range(
                self.field_mapping_widget.count())]
        if len(group_names) == 0:
            header_text = tr(
                'There is no field group for this layer. Please select '
                'another layer.')
            self.header_label.setText(header_text)
            return
        elif len(group_names) == 1:
            pretty_group_name = group_names[0]
        elif len(group_names) == 2:
            pretty_group_name = group_names[0] + tr(' and ') + group_names[1]
        else:
            pretty_group_name = ', '.join(group_names[:-1])
            pretty_group_name += tr(', and {0}').format(group_names[-1])
        header_text = tr(
            'Please fill the information for every tab to determine the '
            'attribute for {0} group.').format(pretty_group_name)
        self.header_label.setText(header_text)
830368
public final void copyPrimitiveField(Object source, Object copy, Field field) {
		copyPrimitiveAtOffset(source, copy, field.getType(), getObjectFieldOffset(field));
	}
325965
def set_fields(self, **fields):
        
        for field_name, value in iteritems(fields):
            field = getattr(self, field_name)
            field.proxy_set(value)
163761
def layer_changed(self, layer):
        
        if not layer:
            enable_keyword_wizard = False
        elif not hasattr(layer, 'providerType'):
            enable_keyword_wizard = False
        elif layer.providerType() == 'wms':
            enable_keyword_wizard = False
        else:
            enable_keyword_wizard = True

        try:
            if layer:
                if is_raster_layer(layer):
                    enable_field_mapping_tool = False
                else:
                    keywords = KeywordIO().read_keywords(layer)
                    keywords_version = keywords.get('keyword_version')
                    if not keywords_version:
                        supported = False
                    else:
                        supported = (
                            is_keyword_version_supported(keywords_version))
                    if not supported:
                        enable_field_mapping_tool = False
                    else:
                        layer_purpose = keywords.get('layer_purpose')

                        if not layer_purpose:
                            enable_field_mapping_tool = False
                        else:
                            if layer_purpose == layer_purpose_exposure['key']:
                                layer_subcategory = keywords.get('exposure')
                            elif layer_purpose == layer_purpose_hazard['key']:
                                layer_subcategory = keywords.get('hazard')
                            else:
                                layer_subcategory = None
                            field_groups = get_field_groups(
                                layer_purpose, layer_subcategory)
                            if len(field_groups) == 0:
                                # No field group, disable field mapping tool.
                                enable_field_mapping_tool = False
                            else:
                                enable_field_mapping_tool = True
            else:
                enable_field_mapping_tool = False
        except (KeywordNotFoundError, NoKeywordsFoundError, MetadataReadError):
            # No keywords, disable field mapping tool.
            enable_field_mapping_tool = False

        self.action_keywords_wizard.setEnabled(enable_keyword_wizard)
        self.action_field_mapping.setEnabled(enable_field_mapping_tool)
30286
def set_fields(
            self,
            new_fields):
        
        self.org_fields = {}
        self.fields_to_add = {}
        for k in new_fields:
            self.org_fields[k] = new_fields[k]
            self.fields_to_add[k] = new_fields[k]