0

I am trying to set a field constraint for a specific field called 'node_id' for node layer. Below is the code:

layer = iface.activeLayer()
field_index = layer.fields().indexFromName("node_id")
constraint_expression = '"node_id"==0 or "node_id" == 1'
layer.setFieldConstraint(field_index, QgsFieldConstraints.Constraint(constraint_expression))
layer.updateFields()

I am facing this error:

ValueError: invalid literal for int() with base 10: '"node_id" not NULL'

Vince
20.5k16 gold badges49 silver badges65 bronze badges
asked Aug 2, 2023 at 10:37

1 Answer 1

0
layer.setFieldConstraint(field_index, QgsFieldConstraints.ConstraintExpression)
layer.setConstraintExpression(field_index, '"node_id" in (0, 1)')
answered Aug 2, 2023 at 11:00
6
  • I want to set an expression like - 'node_id' ==1 or 0 no other value. So thats why I need expression @RainForest Commented Aug 2, 2023 at 11:04
  • I have edited the expression, need to set the expression for the specific field - Node id should have value 0 or 1. Commented Aug 2, 2023 at 11:09
  • Thank you , this works Commented Aug 2, 2023 at 11:32
  • One small question: Is there any way to add a tooltip/placeholder for a field using pyqgis? Commented Aug 4, 2023 at 9:15
  • layer.setFieldAlias(field_index, 'This Field Alias') Commented Aug 4, 2023 at 10:32

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.