Use python to apply a definition query to an existing Layerfile.

606
6
05-15-2012 03:12 AM
GregDreaper
New Contributor II
I will start with I know nothing about python, other than I need it now.  I have created a simple model that uploads a xyz file to a sql table with a survey id, creates an event theme, saves that to a .lyr file, and applies symbology.  However, I need one more thing.

I need some python code that will allow me to apply a definition query to query a single survey id and i need to be able to make it a parameter with the model.  Can anyone help out with this?  Thanks
Tags (2)
0 Kudos
6 Replies
BenjaminGale
New Contributor III
I think this should do the trick.
The attached tool (removed: see attachment in post below) is already setup to be used in a model or on its own.

import arcpy

#Get parameters
lyrName = arcpy.GetParameterAsText(0)
defQuery = arcpy.GetParameterAsText(1)

lyr = arcpy.mapping.Layer(lyrName)
lyr.definitionQuery = defQuery

#Refresh ActiveView
arcpy.RefreshActiveView() 
0 Kudos
GregDreaper
New Contributor II
Perfect.  Exactly what I needed.
0 Kudos
GregDreaper
New Contributor II
As much was I thought this was going to work, it does not on layers that are not within a mxd or arcmap data frame.  It runs, but it does not update the layer file.  Can you help?
0 Kudos
BenjaminGale
New Contributor III
Should be fixed now. 🙂

#==========================
# DEFINITION QUERY
#==========================
# Benjamin Gale - May 2012
#==========================

import arcpy

#Get parameters
lyrName = arcpy.GetParameterAsText(0)
defQuery = arcpy.GetParameterAsText(1)

lyr = arcpy.mapping.Layer(lyrName)
lyr.definitionQuery = defQuery

#Refresh ActiveView
arcpy.RefreshActiveView()
#Save layer (will only occur if the layer is a .lyr file)
lyr.save()
0 Kudos
GregDreaper
New Contributor II
Awesome!  Thanks Buddy!  You have made lives easier.
0 Kudos
GregDreaper
New Contributor II
OK, so everything works great from Catalog or toolbox.  However when I publish to ArcGIS server I get this error, " Geoprocessing service initialization failed.
Invalid parameter: Tool - Survey Loader Tool v2 : Parameter - Input : Data Type - Multiple Value."  I assume the ASCII 3D to Feature Class input parameter is causing this.  Does anyone know a work around?  Thanks!
0 Kudos