[Qgis-user] Create virtual fields with pyQGIS with standalone scripts

Johannes Kröger (WhereGroup) johannes.kroeger at wheregroup.com
Fri Jul 26 07:39:40 PDT 2024


QGIS' virtual fields (expression fields) are not 
https://www.postgresql.org/docs/current/ddl-generated-columns.html

They are conceptually similar between QGIS and PostgreSQL, but they are 
not propagated from QGIS to the data source as a new column there. They 
live only in the QGIS project.

If you want a generated column in your PostgreSQL database, you need to 
add it another way. E.g. via an SQL query.

Cheers, Hannes

On 26.07.24 12:46, Roland Berger via QGIS-User wrote:
> Hi
>
> I would like to add a virtual field to a PostGIS vector layer with 
> PyQGIS with standalone scripts 
> (https://docs.qgis.org/3.34/en/docs/pyqgis_developer_cookbook/intro.html#python-applications)
> All examples I have found so far with google, chatgpt4 and JetBrains 
> AI Assistant gave me solutions that do not work. They only work in the 
> Python Console inside QGIS.
> Does anybody know of a solution that works with PyQGIS with standalone 
> scripts?
> See below what I have tried so far in different variations.
>
> Thanks for any help
> Roland
>
> Example created by chatgpt:
> ...
> field_name = "virtual_field"
> expression = '"attribute_name" * 2'  # Example expression
> # Create and add the virtual field
> layer.startEditing()
> layer.addExpressionField(expression, QgsField(field_name, QVariant.Double))
> layer.commitChanges()
> ...
>
>
>
> _______________________________________________
> QGIS-User mailing list
> QGIS-User at lists.osgeo.org
> List info:https://lists.osgeo.org/mailman/listinfo/qgis-user
> Unsubscribe:https://lists.osgeo.org/mailman/listinfo/qgis-user

-- 
Johannes Kröger / GIS-Entwickler/-Berater

***********************************************************
FOSS Academy Sommerschule: Kompaktkurs zum Aufbau einer GDI
02.-06. September 2024, Präsenzveranstaltung in Bonn
https://www.foss-academy.com/kompaktkurse
***********************************************************

WhereGroup GmbH
c/o KK03 GmbH
Lange Reihe 29
20099 Hamburg
Germany

Tel: +49 (0)228 / 90 90 38 - 36
Fax: +49 (0)228 / 90 90 38 - 11

johannes.kroeger at wheregroup.com
www.wheregroup.com
Geschäftsführer:
Olaf Knopp, Peter Stamm
Amtsgericht Bonn, HRB 9885
-------------------------------
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/qgis-user/attachments/20240726/68ce4947/attachment.htm>


More information about the QGIS-User mailing list