Trying query a hosted feature layer using a variable

390
2
Jump to solution
10-28-2020 10:29 AM
AnthonyAtkins2
New Contributor II

I'm trying to query a hosted feature layer, but instead of having a literal string for the where clause I'm using a variable because the values will change depending on other factors.

Snippet of my code:

parcelList = collectParcels() #collectParcels just reads an excel document of parcel numbers and returns a list
query1 = '\" PARCEL_NO in ' + str(parcelList).replace("[", "(").replace("]", ")") + '\"'
try:
    query_Result = AGOL_Parcels.query(where=query1, return_count_only=True)
    for x in query_Result:
        print(x.as_dict['attributes']['PIN'])
except Exception:
    e = sys.exc_info()[1]
    print(e.args[0])

when I run this code I get this error:

'where' parameter is invalid
(Error Code: 400)

Process finished with exit code 0

Ironically, when I print to the screen, the value of my query1 variable and copy and paste that string value in place of the query1 variable, the code runs perfectly.  I can also remove the where clause entirely and the script runs.

0 Kudos
1 Solution

Accepted Solutions
RandyBurton
MVP Regular Contributor

Depending on parcel numbers being text or integer, try one of the following:

# Text:
query1 = "PARCEL_NO IN ('{}')".format("', '".join(parcelList))

# Integer
query1 = "PARCEL_NO IN ({})".format(", ".join(str(p) for p in parcelList))


>>> parcelList = ['A123', 'B456']
>>> print("PARCEL_NO IN ('{}')".format("', '".join(parcelList)))
PARCEL_NO IN ('A123', 'B456')
>>> parcelList = [123, 456]
>>> print("PARCEL_NO IN ({})".format(", ".join(str(p) for p in parcelList)))
PARCEL_NO IN (123, 456)
‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

View solution in original post

2 Replies
RandyBurton
MVP Regular Contributor

Depending on parcel numbers being text or integer, try one of the following:

# Text:
query1 = "PARCEL_NO IN ('{}')".format("', '".join(parcelList))

# Integer
query1 = "PARCEL_NO IN ({})".format(", ".join(str(p) for p in parcelList))


>>> parcelList = ['A123', 'B456']
>>> print("PARCEL_NO IN ('{}')".format("', '".join(parcelList)))
PARCEL_NO IN ('A123', 'B456')
>>> parcelList = [123, 456]
>>> print("PARCEL_NO IN ({})".format(", ".join(str(p) for p in parcelList)))
PARCEL_NO IN (123, 456)
‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
AnthonyAtkins2
New Contributor II

This worked absolutely perfectly! Thank you!!!

0 Kudos