I try to get features geometry from a polygon layer. I will insert this geometry into one of my postgis table so I think it would be easier if I export the geometry into WKB format. But sadly I just recognise that QgsGeometry doesn't support function to export geometry into wkb format (it's just for wkt and geojson).

enter image description here

Here is my script, but it's using exportToWkt function:

from PyQt4.QtCore import QSettings, QTranslator, qVersion, QCoreApplication
from PyQt4.QtGui import QAction, QIcon
from qgis.core import QgsMapLayer
from qgis.core import QgsFeature, QgsGeometry
selectedLayer =iface.mapCanvas().layers()[0]
for feature in selectedLayer.getFeatures():
    geom = feature.geometry()
    print geom.exportToWkt()

Any ideas to export this geometry into wkb format ?

  • 2
    Did you look to see how the DB manager does it? That's the joy of open source
    – Ian Turton
    Commented Feb 8, 2017 at 18:22

2 Answers 2


See .asWkb() in PyQGIS - Converting WKB to String, and others...

selectedLayer =iface.mapCanvas().layers()[0]
# First feature
elem = selectedLayer.getFeatures().next()
geom= elem.geometry()
print geom.asPoint()

Now, export into wkb format

wkb = geom.asWkb()

Import to ogr geometry

from osgeo import ogr
geom_ogr = ogr.CreateGeometryFromWkb(wkb)
print geom_ogr.GetX(),geom_ogr.GetY(),geom_ogr.GetZ()
205552.628666 89857.6693284 222.199996948

Import to Shapely geometry

from shapely.wkb import loads
point = loads(wkb)
print point.wkt 
POINT Z (205552.628666262 89857.66932836606 222.1999969482422)

Import to PostGIS geometry, look at Importación en PostGIS de capas vectoriales mediante psycopg2 en ambiente de PyQGIS (in Spanish but the scripts are universals)

In the José Guerrero script

ls = wkb.encode('hex')
# Send it to PostGIS
cur.execute('CREATE TABLE my_points(geom geometry, name text)')
   'INSERT INTO my_points(geom, name)'
   'VALUES (ST_SetSRID(%(geom)s::geometry, %(srid)s), %(name)s)',
    {'geom': ls, 'srid': 32612, 'name': 'First point'})
  • 2
    I've tried to use this asWkb() as the solution, but sadly when I try to import it to postgis table it will return error because of the SRID that doesn't match. This solution will return geometry in wkb format and default SRID as 0. How can I change the SRID ? @gene
    – septin
    Commented Feb 9, 2017 at 23:28
  • @septin, did you manage to set the SRID?
    – adamczi
    Commented Feb 16, 2018 at 16:38

One way to transform a PyQGIS feature's geometry to a PostGIS one with the original coordinate system is:

srid = your_layer.crs().postgisSrid()
data = your_feature_in_layer.geometry().asWkt()
sql_fragment = f"ST_GeomFromText('{data}', {srid})"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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