Selection to definition query — Python script works for layers but not standalone tables

613
2
Jump to solution
01-18-2024 10:44 PM
Bud
by
Honored Contributor

ArcGIS Pro 3.2.1

I have a Python script that I use in the Python window to convert a selection to a definition query.

def qdef_selected_features(lyr):
    desc = arcpy.Describe(lyr)
    # Get a semicolon-delimited string of selected feature IDs 
    fid_list = desc.FIDSet.split(";")
    # build the query definition
    query = '{} IN ({})'.format(desc.OIDFieldName, ",".join(fid_list))
    # apply the query definition back to the layer   
    lyr.definitionQuery = query

aprx = arcpy.mp.ArcGISProject('current') 
m = aprx.activeMap 
lyr = m.listLayers('MY_USER.ROADS')[0] 
qdef_selected_features(lyr)

Result:

OBJECTID IN (6, 7, 17, 18, 19, 23, 27, 28)

The script works for feature layers but doesn't work for standalone tables.

Traceback (most recent call last):
File "<string>", line 12, in <module>
IndexError: list index out of range

How can I enhance the script so that it works for non-spatial tables, too?

I'm a novice. Any other tips about improvements would be welcome.

 

Related:

0 Kudos
1 Solution

Accepted Solutions
AlfredBaldenweck
MVP Regular Contributor

So, the problem appears to be that you’re looking for a table in listlayers(). Tables aren’t considered layers since they don’t draw.

Try listTables() instead and see what else you get.

https://pro.arcgis.com/en/pro-app/3.1/arcpy/mapping/map-class.htm

View solution in original post

2 Replies
AlfredBaldenweck
MVP Regular Contributor

So, the problem appears to be that you’re looking for a table in listlayers(). Tables aren’t considered layers since they don’t draw.

Try listTables() instead and see what else you get.

https://pro.arcgis.com/en/pro-app/3.1/arcpy/mapping/map-class.htm

DanPatterson
MVP Esteemed Contributor

and in the Tables class

Table—ArcGIS Pro | Documentation

There is 

  1. listDefinitionQueries ({wildcard})
    Returns a Python list of definition queries associated with a table.

and the ability to get or set them

definitionQuery
(Read and Write)
Provides the ability to get or set a tables's definition query.


... sort of retired...