3

I want to check that a particular features exists or not in getFeature().

Suppose in attribute table I have ID, Name, CAT, and Type columns. Now I want to check that CATEGORY column is exists or not in features.

I use this but this is not working.

for poi in layerPOI.getFeatures():
    if "CATEGORY"  in layerPOI.getFeatures():

and this as well. It producing keyError

if poi["CATEGORY"]#As category not exists it giving error here
  • Can you clarify how you want to check if it exists? Do you want to see if it contains a certain value or a specific value in a specific field...? – Joseph Sep 30 '16 at 11:58
  • want to check specific feature name exists or not – Muhammad Faizan Khan Sep 30 '16 at 11:59
  • You could use some of the methods described in this post: How to read the attribute values using PyQGIS?. And add an if statement to see if the feature exists by matching it to an id or name. – Joseph Sep 30 '16 at 12:04
  • what are the some of the methods. i have already used if it give me error in if condition – Muhammad Faizan Khan Sep 30 '16 at 12:14
  • The term layerPOI.getFeatures() is an iterator and poi is a QgsFeature object. You cannot do if "CATEGORY" in layerPOI.getFeatures() again. – xunilk Sep 30 '16 at 12:14
5

To check if 'CATEGORY' exists as a field:

layer = iface.activeLayer()

field = 'CATEGORY' 

index = layer.fieldNameIndex(field)

if index == -1:
    print "field doesn't exist"
else:
    print "field exists"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.