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")
Solved! Go to Solution.
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(';', ',') + ')'
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(';', ',') + ')'
Thank you so much Johannes, this works! Hope you have a good week 🙂