I'm trying to automate clearing an existing layer definition query and setting a new one. The code I wrote does successfully set the new def query, but it deactivates the old query rather than actually deleting it. The Layer class code sample 2 shows how it presumably would be done, but it doesn't actually delete it. ArcGIS Pro - Modifying Layer Definition query via ArcPY also essentially asks the same question, but it was never fully answered.
for map in aprx.listMaps():
lyr = map.listLayers("Zoning History")[0]
lyr.definitionQuery = None ## have also tried ""
lyr.definitionQuery = "CaseNumber = '" + case + "'"
I've tried setting it as None and "" - both result in deactivating rather than deleting the old query. It's not a showstopper, but it's kind of weird. If I change the def query again, it will overwrite the old-new query, but the old-old query (which was not set using ArcPy, if it matters) still remains present but inactive.
I started thinking about other scenarios, such as what if I wanted to deactivate rather than delete a query? I haven't found any documentation for how to do that properly (rather than unintentionally) with ArcPy.
Thanks for this. I
Here is the code that should do what you want:
import arcpy
# Access the active project
aprx = arcpy.mp.ArcGISProject("CURRENT")
# Access the active map
map_obj = aprx.activeMap
# Check if there is an active map
if map_obj is None:
print("No active map found.")
else:
# Access layers in the active map
layers = map_obj.listLayers()
# Loop through all layers and remove their definition queries
for layer in layers:
if layer.supports("DEFINITIONQUERY"):
try:
# Update the definition query with an empty list to remove it
layer.updateDefinitionQueries([]) # Attempt to clear the query
print(f"Definition query for '{layer.name}' removed.")
except Exception as e:
print(f"Failed to update definition query for '{layer.name}': {e}")
# Save the project
aprx.save()
# Clean up
del aprx
This solution works great. Thank you Miralem.