Tuesday, 21 June 2016

arcgis 10.2 - Setting Definition Query on ArcPy layer from shapefile?


I'm 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.


I want to set a definition query on the layer that I create from using this geoprocessor.


Is this possible?



Answer



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

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...