7

With PyQGIS I want to aggregate some fields in my layer. When I use:

mylayer.aggregate(QgsAggregateCalculator.StringConcatenate, myField)

Then I get a concatenated string without a delimiter. So I tried to add one but failed.

mylayer.aggregate(QgsAggregateCalculator.StringConcatenate, myField, delimiter=',')

QgsVectorLayerr.aggregate():'delimiter' is not a valid keyword argument

mylayer.aggregate(QgsAggregateCalculator.StringConcatenate, myField,
                  QgsAggregateCalculator.AggregateParameters(delimiter=',')) 

'delimiter' is an unknown keyword argument

mylayer.aggregate(QgsAggregateCalculator.StringConcatenate, myField, 
                  QgsAggregateCalculator.AggregateParameters(delimiter(','))) 

name 'delimiter' not defined

mylayer.aggregate(QgsAggregateCalculator.StringConcatenate, myField,
                  QgsAggregateCalculator.AggregateParameters.delimiter(','))

'AggregateParameters' object attribute 'delimiter' is an instance attribute

mylayer.aggregate(QgsAggregateCalculator.StringConcatenate, myField,
                  QgsAggregateCalculator.AggregateParameters.setDelimiter(','))

AttributeError: type object 'AggregateParameters' has no attribute 'setDelimiter'

mylayer.aggregate(QgsAggregateCalculator.StringConcatenate, myField,
                  QgsAggregateCalculator.delimiter(','))

TypeError: QgsAggregateCalculator.delimiter(): first argument of unbound method must have type 'QgsAggregateCalculator'

The help, that shows up when I type the expression, says:

aggregate(QgsAggregateCalculator.Aggregate, QString, QgsAggregateCalculator.AggregateParameters parameters=QgsAggregateCalculator.AggregateParameters(), QgsExpressionContext context=None)

It looks like, if you don't provide parameters, it would use the standard parameters. So I tried QgsAggregateCalculator(mylayer).setDelimiter(','), but that doesn't make any difference. The concatenated string still doesn't contain a delimiter.

So what am I missing here?

1 Answer 1

7

Use the QgsAggregateCalculator like this:

params = QgsAggregateCalculator.AggregateParameters()
params.delimiter = ","

aggr = mylayer.aggregate(QgsAggregateCalculator.StringConcatenate, myField, params)

enter image description here

1
  • Thanks a lot, this works. I think, i wouldn't have found this solution in years.
    – André
    Feb 12, 2022 at 14:54

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .