Sum rows of columns in Data Grid

Hello Anvil Community.
In a Data Grid, displaying the sum of a column, such as the sales column, should be a simple task, but for beginners it can be a difficult task, so I’m sharing 3 examples of how to do it.

Example 1, Using datagrid as a component and properties.

class reporte_diario_partida(reporte_diario_partidaTemplate):
  def __init__(self, fila_partida, **properties):
    # Set Form properties and Data Bindings.
    self.init_components(**properties)
    self.fila_partida = fila_partida
    self.cargar_datagrid()
    self.actualizar_componentes()
    self.label_6.border ="1px solid LightGray"
    self.label_7.border ="1px solid LightGray"
    self.label_8.border ="1px solid LightGray"

  def cargar_datagrid(self):
    if self.fila_partida:
      lineas = list(anvil.server.call('obtener_lineas_partida', self.fila_partida['NumPda'], 'DR'))
  
      # Calcular totales
      total_debito = sum(f["Debito"] or 0 for f in lineas)
      total_credito = sum(f["Credito"] or 0 for f in lineas)
  
      # Crear la fila de totales
      fila_total = {
        "Centro_Costo": None,
        "Cuenta_Contable": {"Codigo": "", "Nombre": "TOTALES"},
        "Comentario": "",
        "Debito": total_debito,
        "Credito": total_credito
      }
  
      # Agregar la fila de totales al final
      lineas.append(fila_total)
  
      # Asignar al repeating panel
      self.repeating_panel_1.items = lineas

  def actualizar_componentes(self):
    self.lblPartida.text = self.fila_partida['NumPda']
    self.lblOrigen.text = "DR"
    self.lblFecha.text = self.fila_partida['Fecha'].strftime('%d/%m/%Y')  # formato bonito
    self.lblComentario.text = self.fila_partida['Comentario']

Example 2, Create and manipulate data grid with code. formatted, Sum the lines in the Debit and Credit columns, Displays rows linked to other tables.

class Form2(Form2Template):
  def __init__(self, **properties):
    self.init_components(**properties)

    # Crear el DataGrid
    self.mi_datagrid = DataGrid()
    self.mi_datagrid.role = 'tonal-data-grid' #✅FORMATTED
    self.mi_datagrid.columns = [
      {"id": "NumPda", "title": "NumPda", "data_key": "NumPda"},
      {"id": "Origen_pda", "title": "Origen", "data_key": "Origen_pda"},
      {"id": "Centro_Costo", "title": "Centro Costo", "data_key": "Centro_Costo"},
      {"id": "Cuenta_Contable", "title": "Cuenta Contable", "data_key": "Cuenta_Contable"},
      {"id": "Comentario", "title": "Comentario", "data_key": "Comentario"},
      {"id": "Debito", "title": "Débito", "data_key": "Debito"},
      {"id": "Credito", "title": "Crédito", "data_key": "Credito"},
    ]

    # Agregar al panel column_panel_1
    self.column_panel_1.add_component(self.mi_datagrid)

    # Encabezado personalizado (opcional)
    encabezado = DataRowPanel()
    encabezado.add_component(
      Label(
        text="📄 Resumen de Operaciones Contables",
        background="#eeeeee",
        bold=True,
        align="center",
        font_size=16
      ),
      full_width_row=True,
    )
    self.mi_datagrid.add_component(encabezado)

    # Obtener datos
    datos = list(app_tables.contabilidad.search(tables.order_by('Fecha', ascending=False), NumPda=75))

    # Inicializar totales
    total_debito = 0
    total_credito = 0

    # Agregar filas al DataGrid
    for fila in datos:
      fila_panel = DataRowPanel()
      fila_panel.add_component(Label(text=str(fila['NumPda'])), column="NumPda")
      fila_panel.add_component(Label(text=str(fila['Origen_pda'])), column="Origen_pda")

      # Centro de Costo
      centro = fila['Centro_Costo']
      fila_panel.add_component(Label(text=centro['Nombre_cc'] if centro else ""), column="Centro_Costo")

      # Cuenta Contable
      cuenta = fila['Cuenta_Contable']
      if cuenta:
        fila_panel.add_component(Label(text=f"{cuenta['Codigo']} - {cuenta['Nombre']}"), column="Cuenta_Contable")
      else:
        fila_panel.add_component(Label(text=""), column="Cuenta_Contable")

      fila_panel.add_component(Label(text=fila['Comentario'] or ""), column="Comentario")

      debito = fila['Debito'] or 0
      credito = fila['Credito'] or 0

      fila_panel.add_component(Label(text=f"{debito:,.2f}"), column="Debito")
      fila_panel.add_component(Label(text=f"{credito:,.2f}"), column="Credito")

      total_debito += debito
      total_credito += credito

      self.mi_datagrid.add_component(fila_panel)

    # Fila resumen de totales
    fila_total = DataRowPanel()
    fila_total.add_component(Label(text=""), column="NumPda")
    fila_total.add_component(Label(text=""), column="Origen_pda")
    fila_total.add_component(Label(text=""), column="Centro_Costo")
    fila_total.add_component(Label(text="TOTALES:", bold=True), column="Cuenta_Contable")
    fila_total.add_component(Label(text=""), column="Comentario")
    fila_total.add_component(Label(text=f"{total_debito:,.2f}", bold=True), column="Debito")
    fila_total.add_component(Label(text=f"{total_credito:,.2f}", bold=True), column="Credito")

    self.mi_datagrid.add_component(fila_total)

Example 3,

class Form1(Form1Template):
  def __init__(self, **properties):
    # Set Form properties and Data Bindings.
    self.init_components(**properties)
    # Crear el DataGrid
    self.mi_datagrid = DataGrid()
    self.mi_datagrid.columns = [
      { "id": "nombre", "title": "Nombre", "data_key": "nombre" },
      { "id": "edad", "title": "Edad", "data_key": "edad" }
    ]

    # Agregarlo al formulario (a un ColumnPanel)
    self.column_panel_1.add_component(self.mi_datagrid)

    # Encabezado personalizado
    title_row = DataRowPanel()
    title_row.add_component(Label(text="My Favourite People",
                                  background='#dddddd',
                                  bold=True,
                                  align='center'),
                            full_width_row=True)
    self.mi_datagrid.add_component(title_row)

    # Datos de ejemplo
    datos = [
      {"nombre": "Ana", "edad": 25},
      {"nombre": "Luis", "edad": 30},
      {"nombre": "Carlos", "edad": 22}
    ]

    # Agregar filas
    total_edad = 0
    for fila in datos:
      fila_panel = DataRowPanel()
      fila_panel.add_component(Label(text=fila["nombre"]), column="nombre")
      fila_panel.add_component(Label(text=str(fila["edad"])), column="edad")
      self.mi_datagrid.add_component(fila_panel)
      total_edad += fila["edad"]

    # Fila resumen de total
    fila_total = DataRowPanel()
    fila_total.add_component(Label(text="Total:", bold=True), column="nombre")
    fila_total.add_component(Label(text=str(total_edad), bold=True), column="edad")
    self.mi_datagrid.add_component(fila_total)
6 Likes