Is there any way to use QGIS variable values in QGIS query builder?

I would like to create a dynamic query which will load data from PostGIS based on a string value which equals the QGIS project filename. Like this:

"project_name" =  base_file_name(  @project_filename )
  • 3
    Where did you want to input your query ? is it for filtering what is fetched from the database or for selecting in a layer or for creating a query layer or ...
    – J.R
    Sep 28 at 8:52
  • The "Query builder" is one for filtering data fetched from the database.
    – etrimaille
    Sep 28 at 10:06

You need to use a QGIS Python Macro. QGIS Expression is not supported in the Query Builder.

Go in Project properties then Macros, the code is under the screenshot :

Project properties macro

Python code to use, you need to replace the layer_id variable :

from qgis.core import QgsProject
def openProject():
    project = QgsProject.instance()
    base_name = project.baseName()

    # Replace by the layer ID you need to filter, print(iface.activeLayer().id()) to have it
    layer_id = "observations_4a0f00d1_eba6_41b7_b196_1ee04ff3d50e"

    layer = project.mapLayer(layer_id)
    layer.setSubsetString("\"project_name\" = '{}'".format(base_name))

  • why two functions closeProject() and saveProject() are required?
    – Taras
    Sep 28 at 11:09
  • 1
    They are not required. They are just by default when you open this tab in QGIS, with an empty project : openProject, saveProject and closeProject. I will remove.
    – etrimaille
    Sep 28 at 11:21
  • it runs on error: Layer tablename: ERROR: column "somestring" does not exist LINE 1: ...T * FROM "public"."tablename" WHERE project_name = Somestring... I guess because the last row above inserting it without ' character.
    – Tamas Kosa
    Sep 28 at 15:38
  • Yes, I have fixed colunm and string formatting with " and '. You can still upvote if it works. I was trying with a integer sorry.
    – etrimaille
    Sep 28 at 15:45
  • 1
    Brilliant, it works
    – Tamas Kosa
    Sep 28 at 15:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.