This is a quick and easy way to get around the problem..but doesn't fix the error. This method works in the python window.
This design is often used inside of loops, and I'm unsure if the Field Calculator will accept it.
try:
#the code you want to work goes here
except: #handles the error
#print "an error occurred, but I can continue to work"
pass
You can use the code below:
lyr = iface.activeLayer()
lyr.dataProvider().addAttributes([QgsField('FromNode', QVariant.String, '', 20)])
lyr.updateFields()
fld_idx = lyr.fields().lookupField('FromNode')
for count, f in enumerate(lyr.getFeatures()):
lyr.dataProvider().changeAttributeValues({f.id(): {fld_idx: f'name{count+1}'}})
Edit in response to further request in comment (start count at 6000):
lyr = iface.activeLayer()
lyr.dataProvider().addAttributes([QgsField('FromNode', QVariant.String, '', 20)])
lyr.updateFields()
fld_idx = lyr.fields().lookupField('FromNode')
count = 6000
for f in lyr.getFeatures():
lyr.dataProvider().changeAttributeValues({f.id(): {fld_idx: f'name{count}'}})
count += 1
Edit 2 in response to further subsequent request. After running the code above to add and populate the 'FromNode' field, run the code below:
lyr = iface.activeLayer()
fld_list = [QgsField('baseVoltag', QVariant.String, '', 20),
QgsField('headTermin', QVariant.String, '', 20),
QgsField('class', QVariant.String, '', 20)]
lyr.dataProvider().addAttributes(fld_list)
lyr.updateFields()
fld_values = ['415V', NULL, 'EnergyConsumer']
att_map = {}
for i, fld in enumerate(fld_list):
att_map[lyr.fields().lookupField(fld.name())] = fld_values[i]
for feat in lyr.getFeatures():
lyr.dataProvider().changeAttributeValues({feat.id(): att_map})
Resulting attribute table shown below:
Best Answer
This solution works using the Attribute Editor, but does not work through the Attribute Table.
Select the records you want to update to
NULL
Open the Attribute Editor from the Editor toolbar
If you have more than one feature you want to update, select the top row (this makes any attributes you edit update all selected records)
In the field you want to update, type
<Null>
This will actually set the field to
NULL
for the selected records, and not to the string value"<Null">
. You can confirm this by doing a Select by Attributestextfield is NULL
- if they are trueNULL
they'll be selected.