Calculated fields and button scripts use the Python programming language. The calculation or script is the implementation of a function whose signature is provided for you.
For instance,
is the value of the name_first field in the current record.
For instance,
record.related["location"]
provides the related records for the current record.
For relationships that specify a single record, you can get the value of a field in that record. For instance,
record.related["location"]["name"]
is the value of the name field in the table indicated by the location relationship (often called location::name).
For relationships that specify multiple records, you can use the aggregate functions (sum, count, average) to get overall values. For instance,
record.related["invoice_lines"].sum("total_price")
.
How you test for empty values depends on the type of field:
Non-text fields may be empty, indicating that the user has not entered any value in the field. For instance, Glom does not assume that an empty value in a numeric field should mean 0.
You can test whether a field is empty by using Python's None. For instance:
if(record["contact_id"] == None):
return "No Contact"
else:
return record.related["contacts"]["name_full"]
You might also test whether there are any related records. For instance:
if(record.related["contacts"] == None):
return "No Contact"
else:
return record.related["contacts"]["name_full"]
For text fields, you should check for zero-length strings. It is not possible in Glom to distinguish between zero-length strings and the absence of any string, because there is no advantage to doing so. For instance:
if(record["name_full"] == ""):
return "No Name"
else:
return record["name_full"]
pygda is a python API for the libgda API. The record's connection attribute provides a gda.connection that can be used to access the current database directly. This allows you to run any SQL query, for instance to read data from the database with a SELECT, or to change values in the database with an UPDATE. Note that the connection is already open so you can avoid the difficult work of specifying the connection details.
The record's table_name attribute also provides the name of the current table.
(Note that the record.connection and record.table_name attributes are only available since Glom 1.1.6.)
This example reads all data from the current table and prints the values to the terminal:
# Use the current database's connection
# to get all the data for the current table.
#
# record.connection is an already-open gda.connection object,
# saving us the bother of opening the connection,
# or even knowing the name of the database.
query = "SELECT * FROM %s" % record.table_name
command = gda.Command(query)
data_model = record.connection.execute_single_command(command)
rows = data_model.get_n_rows()
columns = data_model.get_n_columns()
print " Number of columns: ", columns
for i in range(columns):
print " column ", i;
print " name=", data_model.get_column_title(i)
# Find out whether it's the primary key:
field = data_model.describe_column(i)
if field.get_primary_key():
print " (primary key)"
print "\n";
print " Number of rows: ", rows
for row_index in range(rows):
print " row ", row_index;
for col_index in range(columns):
print " value=", data_model.get_value_at(col_index, row_index).get()
print "\n";
Acerca de
Copyrights
- Copyright © 2004 Murray Cumming
- Copyright © 2007 Jorge González (jorgegonz@svn.gnome.org)
Aviso legal
Se otorga permiso para copiar, distribuir y/o modificar este documento bajo los términos de la Licencia de Documentación Libre de GNU, Versión 1.1 o cualquier otra versión posterior publicada por la Free Software Foundation; sin Secciones Invariantes ni Textos de Cubierta Delantera ni Textos de Cubierta Trasera. Puede encontrar una copia de la licencia GFDL en este enlace o en el archivo COPYING-DOCS distribuido con este manual.
Este manual es parte de una colección de manuales de GNOME distribuido bajo la GFDL. Si quiere distribuir este manual por separado de la colección, puede hacerlo añadiendo una copia de la licencia al manual, tal como se describe en la sección 6 de la licencia.
Muchos de los nombres usados por compañías para distinguir sus productos y servicios son mencionados como marcas comerciales. Donde esos nombres aparezcan en cualquier documentación de GNOME, y los miembros del Proyecto de Documentación de GNOME están al corriente de esas marcas comerciales, entonces los nombres se pondrán en mayúsculas o con la inicial en mayúsculas.
ESTE DOCUMENTO Y LAS VERSIONES MODIFICADAS DEL MISMO SE PROPORCIONAN SEGÚN LAS CONDICIONES ESTABLECIDAS EN LA LICENCIA DE DOCUMENTACIÓN LIBRE DE GNU (GFDL) Y TENIENDO EN CUENTA QUE:
-
EL DOCUMENTO SE PROPORCIONA "TAL CUAL", SIN GARANTÍA DE NINGÚN TIPO, NI EXPLÍCITA NI IMPLÍCITA INCLUYENDO, SIN LIMITACIÓN, GARANTÍA DE QUE EL DOCUMENTO O VERSIÓN MODIFICADA DE ÉSTE CAREZCA DE DEFECTOS COMERCIALES, SEA ADECUADO A UN FIN CONCRETO O INCUMPLA ALGUNA NORMATIVA. TODO EL RIESGO RELATIVO A LA CALIDAD, PRECISIÓN Y UTILIDAD DEL DOCUMENTO O SU VERSIÓN MODIFICADA RECAE EN USTED. SI CUALQUIER DOCUMENTO O VERSIÓN MODIFICADA DE AQUÉL RESULTARA DEFECTUOSO EN CUALQUIER ASPECTO, USTED (Y NO EL REDACTOR INICIAL, AUTOR O CONTRIBUYENTE) ASUMIRÁ LOS COSTES DE TODA REPARACIÓN, MANTENIMIENTO O CORRECCIÓN NECESARIOS. ESTA RENUNCIA DE GARANTÍA ES UNA PARTE ESENCIAL DE ESTA LICENCIA. NO SE AUTORIZA EL USO DE NINGÚN DOCUMENTO NI VERSIÓN MODIFICADA DE ÉSTE POR EL PRESENTE, SALVO DENTRO DEL CUMPLIMIENTO DE LA RENUNCIA;Y
-
BAJO NINGUNA CIRCUNSTANCIA NI BAJO NINGUNA TEORÍA LEGAL, SEA POR ERROR (INCLUYENDO NEGLIGENCIA), CONTRATO O DE ALGÚN OTRO MODO, EL AUTOR, EL ESCRITOR INICIAL, CUALQUIER CONTRIBUIDOR, O CUALQUIER DISTRIBUIDOR DEL DOCUMENTO O VERSIÓN MODIFICADA DEL DOCUMENTO, O CUALQUIER PROVEEDOR DE CUALQUIERA DE ESAS PARTES, SERÁ RESPONSABLE ANTE NINGUNA PERSONA POR NINGÚN DAÑO DIRECTO, INDIRECTO, ESPECIAL, INCIDENTAL O DERIVADO DE NINGÚN TIPO, INCLUYENDO, SIN LIMITACIÓN DAÑOS POR PÉRDIDA DE MERCANCÍAS, PARO TÉCNICO, FALLO INFORMÁTICO O MAL FUNCIONAMIENTO O CUALQUIER OTRO POSIBLE DAÑO O PÉRDIDAS DERIVADAS O RELACIONADAS CON EL USO DEL DOCUMENTO O SUS VERSIONES MODIFICADAS, AUNQUE DICHA PARTE HAYA SIDO INFORMADA DE LA POSIBILIDAD DE QUE SE PRODUJESEN DICHOS DAÑOS.
Comentarios
Para informar sobre un error o hacer sugerencias sobre Glom o sobre éste manual, puede enviarlas en la página Gnome Bugzilla, seleccionando el producto Glom. Para asegurarse de que otros no han informado antes del mismo fallo, busque en Bugzilla antes de enviar su error.