Looping through a definition query in data driven pages

7454
12
03-20-2012 03:09 PM
KarlaMayne
New Contributor II
I'm hoping someone can help me with this one; I've read every post I could find and I'm still stuck. I've got a series of data driven pages that I can get to export with no problem, but I also need to update a mask layer while I'm exporting each page. The ddp name is based on state names and the mask layer is also based on state name. I've got a simple definition query that I use to turn the mask layer on and off for each state. For example, the current ddp is Arizona so the definition query on the mask layer would be "STATE_NAME" <> 'Arizona'. This turns the mask layer off for Arizona while leaving the surrounding states grayed out.

Here's the script that I have so far:

import arcpy, sys, os
arcpy.OverWriteOutput = 1
mxd = arcpy.mapping.MapDocument("CURRENT")

print "Enter save as pdf location:"
pdfDir = arcpy.GetParameterAsText(0)
outputFolder = pdfDir + r"\PDFs"

df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
maskLayer = arcpy.mapping.ListLayers(mxd, "state_bnd110", df)[0]
maskField = "STATE_NAME"

for pageNum in range(1, mxd.dataDrivenPages.pageCount + 1):
    mxd.dataDrivenPages.currentPageID = pageNum
    pageName = mxd.dataDrivenPages.pageRow.STATE_NAME
    for lyr in arcpy.mapping.ListLayers(mxd):
        if lyr.name == maskLayer:
            lyr.definitionQuery = '"STATE_NAME" <> pageName'
        arcpy.mapping.ExportToPDF(mxd, os.path.dirname(outputFolder)+ os.sep + pageName + ".pdf")
        lyr.definitionQuery = ""
        arcpy.RefreshActiveView()

del mxd
arcpy.GetMessages()

If I take out the layer loop the script will export all the ddp with no trouble (and with no mask symbology). As the script is now, it will export the first state (Arizona) with all the states grayed out (for this page, Arizona should not be) then it will export Arizona again and again.

Any help would be greatly appreciated!
Karla
Tags (2)
12 Replies
JanetRogers
Occasional Contributor II

Thanks for sharing this.  It is just what I was looking for.

KendrickSchuett
New Contributor II

Thank you very much for the Clean Code and comments as someone new to Python and Arcmap this really helps me understand whats going on. Thanks again I appreciate it.

RustyRex
Occasional Contributor

I agree that is incredibly helpful for folks to post their final code.  Thanks for that.  I do have a question about line-38.  Dont you want "lyr.definitionQuery = query # set the layers defintionQuery  " to be outside of the 'else'?  You want to set the def query to the variable 'query' either way, and NOT just in the case of the else, right?  I cant say for sure, because I am elementary with my python.

0 Kudos