0

I am working on below function trying to get the value in last feature edited in a layer named (route_arc), in an attribute named (serial_number). I already have 2 features in this layer but can't get results and can't figure out where I missed up.

Error (No feature was found on this layer to evaluate the expression)

I am asking for last features where there is nothing after. Then reverse it to get my field value. I am trying to avoid use something like editbuffer() method.

Code :

from qgis.core import QgsProject, QgsFeature, QgsFeatureRequest, QgsVectorLayer
from qgis.utils import qgsfunction

@qgsfunction(args='auto', group='Custom')
def values(layer: QgsVectorLayer, field_name: str) -> str:
    # Get the layer by name
    layer_name = 'route_arc'
    layer = QgsProject.instance().mapLayersByName(layer_name)[0]

    # Define feature request to get the last edited feature
    idfield='did'
    request = QgsFeatureRequest()
    request.setLimit(1)
    request.setOrderBy(idfield, False)

    # Get the last edited feature
    features = layer.getFeatures(request)
    last_edited_feature = next(features, None)
    
    
    if last_edited_feature is not None:
        # Get the attribute value for a specific field
        field_name = 'serial_number'
        field_value = last_edited_feature.attribute(field_name)
        return str(field_value)
    else:
        print('No features found')
2
  • Hi, is it because you are limiting your feature request to 1 feature (request.setLimit(1)) so there will never be a next feature?
    – ian
    Mar 26, 2023 at 10:08
  • Thanks ian, am trying to limit it to only one raw, so I used 1 . api.qgis.org/api/… Mar 26, 2023 at 10:24

1 Answer 1

1

I used the answer from Ian to and change the value to -1

I also used layer Id

from qgis.core import QgsProject, QgsFeature, QgsFeatureRequest, QgsVectorLayer
from qgis.utils import qgsfunction

@qgsfunction(args='auto', group='Custom')

def get_last_added_feature_serial_number(layer_id, fieldserial):
    # Get layer by ID
    layer_id = 'route_arc_6c4adf7a_bade_4420_8ac9_7c754e9e05f2'
    fieldserial = 'serial_number'
    layer = QgsProject.instance().mapLayer(layer_id)

    # Define feature request
    request = QgsFeatureRequest()
    request.setLimit(-1)
    request.addOrderBy('did', False)  # Sort features by descending id

    # Get last added feature
    features = layer.getFeatures(request)
    for feature in features:
        # Retrieve serial number attribute value
        serial_number = feature[fieldserial]
        return serial_number  # Return the serial number value

    # Run:
 

    serial_number = get_last_added_feature_serial_number(layer_id,fieldserial)

Your Answer

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

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