Add a definition Query with python

5350
5
Jump to solution
02-19-2015 12:05 AM
PeterVersteeg
Occasional Contributor II

I want to add a difinition query with python so far i have this

import arcpy  
  
mxd = arcpy.mapping.MapDocument(r"Y:\TRUTTA\Trutta_new\TruttaMaps\test.mxd")


for lyr in arcpy.mapping.ListLayers(mxd, "*"):
    if lyr.name == "chimney_p":
        lyr.definitionQuery = """"Trutta_Map" = '19A4'"""

In my pythonWin it seems to work BUT the query in my shape did not get the new query.

anyone know why that is ?

0 Kudos
1 Solution

Accepted Solutions
OwainCatton
New Contributor III

Hi Peter,

You are missing just the last step, saving the MXD when you have finished editing the layers.

So your code should read.

import arcpy

mxd = arcpy.mapping.MapDocument(r"Y:\TRUTTA\Trutta_new\TruttaMaps\test.mxd")

for lyr in arcpy.mapping.ListLayers(mxd, "*"):
     if lyr.name == "chimney_p":
          lyr.definitionQuery = """"Trutta_Map" = '19A4'"""

mxd.save()

Hope that helps,

Owain

View solution in original post

5 Replies
DanPatterson_Retired
MVP Emeritus

The query may have work, but it isn't going to show up unless you are running the script against "CURRENT" See example 2 in this link  

PeterVersteeg
Occasional Contributor II

thank you Dan this gives my samething to read in the train and learn more about the mapping.

gr Peter

0 Kudos
OwainCatton
New Contributor III

Hi Peter,

You are missing just the last step, saving the MXD when you have finished editing the layers.

So your code should read.

import arcpy

mxd = arcpy.mapping.MapDocument(r"Y:\TRUTTA\Trutta_new\TruttaMaps\test.mxd")

for lyr in arcpy.mapping.ListLayers(mxd, "*"):
     if lyr.name == "chimney_p":
          lyr.definitionQuery = """"Trutta_Map" = '19A4'"""

mxd.save()

Hope that helps,

Owain

PeterVersteeg
Occasional Contributor II

Thank you Owain,

That did the trick. Did not
know about the save part. My fist try was a error because I had the mxd open in
arcmap. In other scripts a had lock errors. Same scripts work even if the mxd
is open. What are the rules for this ? where can I read about it ?

Greetings Peter

0 Kudos
OwainCatton
New Contributor III

Afternoon Peter,

As Dan mentioned above, the use of CURRENT instead of a file path would mean that the Python script will edit the current ArcMap session, where as if you specify the file path the Python script will open a new session, hence the locks errors your were getting as you had the MXD already open.

You can read more here http://resources.arcgis.com/en/help/main/10.2/index.html#//00s30000000r000000

  • MapDocument Example 1
    If you have a the MXD open in ArcMap and want to run a script on its contents use CURRENT
  • MapDocument Example 2
    If you want to run the script independently you specifiy te full File Path

Owain