0

I am trying to set multiple definition queries for one layer based on one field using python. ie. I have a City layer with a field that holds the city name. I want a copy of the layer in an MXD with the Definition query set for each value in the City field. So essentially, I have one source layer, with a copy of the layer as many times as there are values in the City field. The query would look like this: CITY = 'Atlanta'

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
AK47
  • 9
  • 1

2 Answers2

5

This can be achieved with use of a SearchCursor. Let's assume mxd is your map document object, df is your data frame object, and fc is your feature class. Also, CITY is the name of your field. Try something like this:

from arcpy import *

field = "CITY"

env.overwriteOutput = True

#Create cursor to iterate rows
cursor = da.SearchCursor (fc, field)
for row in cursor:
    #sql statement for a single feature
    sql = '"{0}" = \'{1}\''.format (field, row[0])
    #Make layer with sql for one feature only. Name layer City name
    MakeFeatureLayer_management (fc, row[0], sql)   
    #Make mapping layer object
    lyr = mapping.Layer(row[0])
    #Add mapping layer object to map
    mapping.AddLayer (df, lyr)
del cursor
mxd.save ()
Emil Brundage
  • 13,859
  • 3
  • 26
  • 62
3

The Help page on Layer (arcpy.mapping) has sample code at the end which shows a simple loop that you can easily adapt to change the layer property definitionQuery.

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
Hornbydd
  • 43,380
  • 5
  • 41
  • 81
  • I can set the definition query using Python and the layers in the data frame. But, I want it to copy and paste the feature class in the TOC and apply a definition query for every City in the feature class. – AK47 Jul 10 '14 at 19:27