11

I am trying to determine options to set a layer definition query using ArcPy.

I know that it is possible when using arcpy.mapping.ListLayers().

However, in this scenario I am loading in shapefiles, and using arcpy.MakeFeatureLayer_management() in ArcPy.

How do I set a definition query on the layer that I create from using this geoprocessor?

I am using ArcMap 10.2.

16

The code below will create, from a shapefile, a layer file called test_A.lyr which has a Definition Query of "testField" = 'A' saved into it.

import arcpy

arcpy.MakeFeatureLayer_management(r"C:\temp\testLines.shp","test_lyr")
lyr = arcpy.mapping.Layer("test_lyr")
lyr.name = "test"
lyr.definitionQuery = '"testField" = ' + "'A'"
lyr.saveACopy(r"C:\temp\test_A.lyr")

del lyr

If required, you could also add this layer file,or the Layer object (lyr) from prior to it being saved as a layer file, into your map via arcpy.mapping.AddLayer.

To see whether a where_clause on MakeFeatureLayer gets passed through as a Definition Query, which I think is undocumented behaviour, I performed a second test below to verify the Answer of @John, and he is quite correct.

arcpy.MakeFeatureLayer_management(r"C:\temp\testLines.shp","test_lyr2",'"testField" = ' + "'A'")
lyr2 = arcpy.mapping.Layer("test_lyr2")
lyr2.name = "test2"
lyr2.saveACopy(r"C:\temp\test_2.lyr")

del lyr2
| improve this answer | |
5

Yes, it should definitely be possible for you as that is what the optional "where_clause" parameter is for - see its documentation for details and examples, but basically you just need to include the definition query as the where_clause param and it should work. Only thing to note, if you are using a layer that doesn't have an ObjectID/FID field, ArcGIS has issues running SQL expressions against it, but any regular ArcGIS layer will.

| improve this answer | |
4

If you are loading layers into Arcmap using the MakeFeatureLayer geoprocessing tool, you can set the definitionQuery on existing arcmap layers using the arcpy.mapping class layers - definitionQuery.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.