ArcPy – Setting Definition Query Name in ArcGIS Pro

arcgis-proarcpydefinition-query

I am using ArcGIS Pro 2.9

Using ArcPy I have to initiate multiple queries every day on 60+ layers and all these queries are piling up in Definition query tab for all these layers.
I am unable to delete the queries using

lyr.definitionQuery = ""

OR

lyr.definitionQuery = None

both just deactivate the queries.

Is there a way to reuse the existing definition query again, like if using query name, using ArcPy?

Update:

Even replacing query did not help, what I tried is as follow

Old_DT = lyr.definitionQuery
New_DT = lyr.definitionQuery.replace(Old_DT,DT)
lyr.definitionQuery = New_DT

Still New query is added in query definition list.

Best Answer

You can use CIM to manipulate multiple definition queries that a layer may have, below is some sample code to demonstrate this. In this example the layer already has a Query Definition called "SillyQuery" imposed upon it. As you have spotted simply editing it causes a new query to be inserted into the list. This seems to be default behaviour that one cannot override but as it appears to be the query added to the end of the list, this code simply removes it and overwrites the list, this is how it stops the ever growing list of query definitions.

import arcpy
p = arcpy.mp.ArcGISProject('current')
m = p.listMaps('Map')[0]
l = m.listLayers('Cables')[0] # Example layer

# Return the layer's CIM definition
l_cim = l.getDefinition('V2')

# Get Feature Table object
fTab = l_cim.featureTable

# Get the Query Definition Name, this assumes one is active
expName = fTab.definitionExpressionName

# If SillyQuery is active then adjust the expression
if expName == "SillyQuery":
    fTab.definitionExpression = "OBJECTID = 2"
    # This causes an insert of a new entry into the list
    
# Remove new entry in list
aList = fTab.definitionFilterChoices
aList = aList[:-1]
fTab.definitionFilterChoices = aList

# Push the changes back to the layer object
l.setDefinition(l_cim)