[GIS] Updating ESRI mxd definition query variable via python

arcpydefinition-query

we use definition queries to filter data to field users. We have up to 40-50 MXDs that are identical except for 1 variable in the definition query that allows the data for that MXD to be unique.
Example – "DeploymentNumber='AA'" where 'AA' is the variable.
So, when we update MXDs, we would like to be able to use a python script to be able to update the variable – 'AA' component of our definition query in each layer without having to open each MXD, click on each layer and manually update (which in some cases is a 5 minute operation per MXD).

Best Answer

You'll have to change this for your specific data since there might be layers that you don't want to change / don't have def queries set:

import os
import arcpy

# top level directory where all the map docs are
path = r"<path>" 

# recursively search the directory for .mxd files
def getMXD(path):
    for dirpath, dirnames, filenames in os.walk(path):
        for f in filenames:
            if f.endswith(".mxd"):
                yield os.path.join(dirpath, f)


for mapdoc in getMXD(path):
    # might need to change wildcarding here
    mxd = arcpy.mapping.MapDocument(mapdoc) 
    df = arcpy.mapping.ListDataFrames(mxd, "*")[0]

    for lyr in arcpy.mapping.ListLayers(mxd, "*", df):        
        if lyr.supports("DEFINITIONQUERY"):
            lyr.definitionQuery = "DeploymentNumber = 'AA'"
            mxd.save() # or mxd.saveACopy(<newpath>)

    del mxd, df
Related Question