Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python SQLAlchemy: Mapping a PostGIS geom field

SQLAlchemy maps DB columns to object members in Python. For example:

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
    name = Column(String(50))
    fullname = Column(String(50))
    password = Column(String(12))

Which type should be used to map a PostGIS geom column to a class member?

like image 750
Adam Matan Avatar asked Aug 20 '14 13:08

Adam Matan


1 Answers

As far as I know, there's no built in way to do this with SQLAlchemy. However, GeoAlchemy2 is an extension to SQLAlchemy that adds support for geospatial fields (points, lines, polygons, etc):

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Sequence
from geoalchemy2 import Geometry

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
    name = Column(String(50))
    fullname = Column(String(50))
    password = Column(String(12))
    geom = Column(Geometry('POINT'))

GeoAlchemy2 also provides functionality for spatial queries. From the docs:

query = session.query(Lake).filter(Lake.geom.ST_Contains('POINT(4 1)'))
like image 124
danpelota Avatar answered Oct 25 '22 05:10

danpelota