HOW TO

Auto-populate attribute fields in a hosted feature layer using Python

Last Published: October 3, 2022

Summary

When adding new features to data layers, attributes can be added and edited too. When working with a geodatabase, attribute rules can be used to automatically populate attributes, restrict invalid edits during edit operations, and perform quality assurance checks on existing features. Feature layers can also be published with attribute rules as registered data to your Enterprise environment. By doing this, the attribute rules are applied when edits are made to the referenced layer. 

However, attribute rules are not yet supported in ArcGIS Online, but it may be desirable to automatically populate an attribute field when collecting data to a layer hosted on ArcGIS Online. As an alternative, you can leverage Smart Form capabilities in ArcGIS Field Maps and add calculated expressions to the form that enables automatically calculating and populating data in the form using an Arcade expression. This can be also done post data collection by editing data in the attribute table. You can use Field Calculator in ArcGIS Online or Desktop to calculate values for any of the attribute fields. However, manual calculation may not be a viable solution, especially when working with a large dataset. Additionally, you may prefer to automate this process to have a more efficient workflow. 

Procedure

This can be done using ArcGIS API for Python to update the attributes for the features in a hosted feature layer.  

 The sample script below calculates the values in a field named "TargetField" for a subset of features (with dates after Jan 15, 2022 in the "DateField" field) by concatenating existing values in two other fields (i.e. "Field1" and "Field2").  If the "TargetField" has existing values, they are overwritten by the new values after updating features with this script. 

#log in to Portal/ArcGIS Online
from arcgis.gis import GIS
gis = GIS('https://arcgis.com/', "Username", "Password")

#find the hosted feature layer
hfl = gis.content.get("ItemID")
hflayer =hfl.layers[0]

#query the features that need to be updated
fset = hflayer.query(where = 'DateField > DATE \'2022-01-15\'')

# updating selected features' attribute
for f in (fset.features):
  f.attributes['TargetField'] = str(f.attributes['Field1']) + "_" + str(f.attributes['Field2'])
  hflayer.edit_features(updates = fset.features)

print ('Attributes were successfully updated!')

This process can be automated by running the script using a third-party app like Windows Task Scheduler or use ArcGIS Notebooks Tasks: 
ArcGIS Online: Schedule a notebook task

Article ID:000027245

Software:
  • ArcGIS Online
  • ArcGIS API for Python
  • ArcGIS Pro 3 0
  • ArcGIS Pro 2 8 x
  • ArcGIS Pro 2 x

Get help from ArcGIS experts

Contact technical support

Download the Esri Support App

Go to download options

Related Information

Discover more on this topic