4

I'm trying to develop a python code that will apply the same definition query to all layers in a specified group. I currently have a working code that will apply a definition query to all layers in the Table of Contents, but unfortunately I need it to apply the syntax to a specific group of layers. Any ideas?

I've seen this post:

Create a definition query for groups of layers: Is it possible?

But when I set it up specific to my mxd project, nothing happens.

import arcpy

#Variables to form query syntax
#-------------------------------------------
#field in Attribute table
field = 'Country \n'
queryField = '"%s"' % field.strip()   #add double quotes field (for query syntax)
#value in specified field
value = "'Canada'"
#concatenate query syntax
queryStr = str(queryField) + "=" + str(value)
#--------------------------------------------
mxd = arcpy.mapping.MapDocument("CURRENT")

for lyr in arcpy.mapping.ListLayers(mxd):
    if lyr.supports("DEFINITIONQUERY"): 
        lyr.definitionQuery = queryStr
arcpy.RefreshActiveView()       
del mxd
  • How are you running your script? It must be run as a script tool or from the ArcMap Python window to be run in-process, which allows the "CURRENT" map document to be modified. – blah238 Jun 29 '12 at 15:23
  • Just running it in the python window for now. – Czed Jun 29 '12 at 15:29
3

Okay I got it, thanks anyways! It's a little bit more elegant now.

import arcpy

#Variables to form defintion query
field = '"Country"'
value = "'Canada'"
#concatenate query syntax
queryStr = str(field) + "=" + str(value)
#Specify the MXD project (CURRENT), dataframe (Layers)
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
#Apply defintion query to specified layer group (Test)
for lyr in arcpy.mapping.ListLayers(mxd, "Test", df)[0]:
    if lyr.supports("DEFINITIONQUERY"): 
        lyr.definitionQuery = queryStr
arcpy.RefreshActiveView()       
del mxd

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.