Python SQLAlchemy: Mapping a PostGIS geom field
Question: SQLAlchemy maps DB columns to object members in Python. [For
example](http://docs.sqlalchemy.org/en/rel_0_9/orm/tutorial.html):

    
    
    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](http://dba.stackexchange.com/a/71779/972) to a class member?


Answer: As far as I know, there's no built in way to do this with SQLAlchemy. However,
[GeoAlchemy2](https://github.com/geoalchemy/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](https://geoalchemy-2.readthedocs.org/en/0.2.4/orm_tutorial.html#spatial-
query):

    
    
    query = session.query(Lake).filter(Lake.geom.ST_Contains('POINT(4 1)'))
    

