0

I am using ArcMap 10.6 and I try to run a script in ArcMap in order to apply a certain definition query on all project layers that support definition queries.

# -*- coding: UTF-8 -*-
# import system modules
import arcpy
import sys
import os

script = sys.argv[0]
arcpy.AddMessage('running script =' + script)

# single run lines
mxd = arcpy.mapping.MapDocument("CURRENT")
dataFrame = arcpy.mapping.ListDataFrames(mxd)[0] #[0] for first dataframe
layerlist = arcpy.mapping.ListLayers(dataFrame)

Param = arcpy.GetParameterAsText(7) #0-6 are already reserved

# for loop
for layer in layerlist:
   arcpy.AddMessage(layer.name)
   if layer.supports("definitionQuery"):
      try:
         z = layer.definitionQuery ("NAME_PROJECT = %s") %(Param)
         layer.definitionQuery = z
      except:
         print("Layer does not support definition query.")
         arcpy.AddMessage(layer)

# refreshing
arcpy.RefreshActiveView()

As you see, what the script does so far is just to check if layers support definition queries and if so to apply such a one that filters layers that have String based values in attribute field named "NAME_PROJECT". The script seems to successfully filter by afore-mentioned query but it does not show the definition query in the layer´s properties.

2
  • If the field NAME_PROJECT is text, then your comparison will fail because the constant isn't quoted with apostrophes.
    – Vince
    Oct 6, 2022 at 16:33
  • ListLayers (mxd) is a way to go.
    – FelixIP
    Oct 7, 2022 at 4:07

1 Answer 1

1

You have a test already to see if def query is supported so you are not testing for this in the try/except, you are catching a failure. It is possibly an error in the line

z = layer.definitionQuery ("NAME_PROJECT = %s") %(Param)

Attempt the below.

# for loop, iterate through the layers
for layer in layerlist:
   # print the layer name so you can see if success or fail
   arcpy.AddMessage(layer.name)
   # check if the layer supports def query and if it does
   if layer.supports("definitionQuery"):
      # try add a def query
      try:
         z = "NAME_PROJECT = '{0}'".format(Param)
         layer.definitionQuery = z
         arcpy.AddMessage("Success")
      # if it fails to add a def query then say so
      except:
         arcpy.AddMessage("Failed to apply def query")
   # if def query is not supported then say so       
   else:
         arcpy.AddMessage("Layer does not support definition query.")
         

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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