4

I have the following script to merge a group of layers, and I want to edit the script to add a field containing today's date in the attribute table and also delete some fields by their names?

root = QgsProject.instance().layerTreeRoot()
group = root.findGroup("RL")
layers = [layer.layer() for layer in group.children()]

merged = processing.run("native:mergevectorlayers", {'LAYERS': layers, 'OUTPUT':"TEMPORARY_OUTPUT"})["OUTPUT"]

QgsProject.instance().addMapLayer(merged, False) root.insertLayer(0, merged)

Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389
Ahmed Kamel
  • 429
  • 2
  • 6
  • we can add the date with the advanced python field calculator, but I want to add it with a python script and this is not shown in the link you shared – Ahmed Kamel Jan 20 '22 at 14:08

2 Answers2

6

You can use this script:

from datetime import date

previous lines

provider = merged.dataProvider()

add date field

i = merged.fields().indexFromName("date") if i == -1: provider.addAttributes([QgsField('date', QVariant.Date)]) merged.updateFields()

populate date field

i = merged.fields().indexFromName("date") attr_map = {f.id(): {i: QDate(date.today())} for f in merged.getFeatures()} provider.changeAttributeValues(attr_map)

delete some fields

field_names = ['Shape'] # field names to be deleted field_indices = [merged.fields().indexFromName(f) for f in field_names] provider.deleteAttributes(field_indices) merged.updateFields()

QgsProject.instance().addMapLayer(merged, False) root.insertLayer(0, merged) ``

Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389
3

One easy way is to execute Refactor field manually. Add the field and calculate with the expression now(), and delete whatever fields you like:

enter image description here

Then press Ctrl+Alt+H and copy paste the code:

processing.run("native:refactorfields", {'INPUT':'C:/GIS/data/tempdata/grid.shp','FIELDS_MAPPING':[{'expression': '\"id\"','length': 20,'name': 'id','precision': 0,'type': 6},{'expression': '\"left\"','length': 23,'name': 'left','precision': 15,'type': 6},{'expression': '\"top\"','length': 23,'name': 'top','precision': 15,'type': 6},{'expression': '\"right\"','length': 23,'name': 'right','precision': 15,'type': 6},{'expression': '\"bottom\"','length': 23,'name': 'bottom','precision': 15,'type': 6},{'expression': 'now()','length': 0,'name': 'now','precision': 0,'type': 14}],'OUTPUT':'TEMPORARY_OUTPUT'})
BERA
  • 72,339
  • 13
  • 72
  • 161