How Can I Set a Definition Query from a Selection in Arcpy?

582
2
Jump to solution
01-06-2023 02:38 PM
Labels (3)
rescobar
New Contributor III

Hello, I am trying to get a script to set a definition query from a selection. The selection is set by using an intersect from a buffer layer. I know the first part works, because if I just run this, it will create a selection in the mxd. I have also tested the second 'for...' with an mxd open and it works. However, I need to run this with the mxd closed, as it is being newly created. All I get is "OBJECTID IN ()" in the county layer's query.

 

 

 

 

 

        for lyr in arcpy.mapping.ListLayers (mxd,'HALF_MILE_BUFFER'):
            county_lyr = arcpy.mapping.ListLayers(mxd, 'County')[0]
            arcpy.SelectLayerByLocation_management(county_lyr,"INTERSECT",lyr)
            
        for lyr in arcpy.mapping.ListLayers (mxd,'County'):   
            fids = arcpy.Describe(lyr).FIDSet
            idfield = 'OBJECTID'
            wc = idfield + ' IN (' + fids.replace(';',',') + ')'
            county_lyr.definitionQuery = wc
            arcpy.SelectLayerByAttribute_management(lyr, "CLEAR_SELECTION")

 

 

 

 

 

0 Kudos
1 Solution

Accepted Solutions
JohannesLindner
MVP Frequent Contributor

Can't test in ArcMap, but I saw the same behavior in ArcGIS Pro. I could solve it by creating a new layer in memory:

buffer_lyr = arcpy.mapping.ListLayers (mxd,'HALF_MILE_BUFFER')[0]

# get the layer in the map
county_lyr_in_map = arcpy.mapping.ListLayers(mxd, 'County')[0]
# create a new layer using the map layer's data source
county_lyr = arcpy.management.MakeFeatureLayer(county_lyr_in_map.dataSource, "SomeName")
# select in that new layer
arcpy.management.SelectLayerByLocation(county_lyr, "INTERSECT", buffer_lyr)
# set the definition query in the map layer
fids = arcpy.Describe(county_lyr).FIDSet
county_lyr_in_map.definitionQuery = 'OBJECTID IN (' + fids.replace(';', ',') + ')'

 


Have a great day!
Johannes

View solution in original post

0 Kudos
2 Replies
JohannesLindner
MVP Frequent Contributor

Can't test in ArcMap, but I saw the same behavior in ArcGIS Pro. I could solve it by creating a new layer in memory:

buffer_lyr = arcpy.mapping.ListLayers (mxd,'HALF_MILE_BUFFER')[0]

# get the layer in the map
county_lyr_in_map = arcpy.mapping.ListLayers(mxd, 'County')[0]
# create a new layer using the map layer's data source
county_lyr = arcpy.management.MakeFeatureLayer(county_lyr_in_map.dataSource, "SomeName")
# select in that new layer
arcpy.management.SelectLayerByLocation(county_lyr, "INTERSECT", buffer_lyr)
# set the definition query in the map layer
fids = arcpy.Describe(county_lyr).FIDSet
county_lyr_in_map.definitionQuery = 'OBJECTID IN (' + fids.replace(';', ',') + ')'

 


Have a great day!
Johannes
0 Kudos
rescobar
New Contributor III

Thank you so much Johannes, this works! Hope you have a good week 🙂

0 Kudos