Select to view content in your preferred language

Add a definition Query with python

5685
5
Jump to solution
02-19-2015 12:05 AM
PeterVersteeg
Frequent Contributor

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
Regular Contributor

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
Frequent Contributor

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

gr Peter

0 Kudos
OwainCatton
Regular Contributor

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
Frequent Contributor

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
Regular Contributor

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