Search code examples
flaskgeoalchemy2

Correct json format to save into geoalchemy2 Geometry field


I have a json of this format:

{

     "type":"Feature",
     "properties":{},
     "geometry":{
          "type":"Point",
          "coordinates":[6.74285888671875,-3.6778915094650726]
     }
}

And a flask-geoalchemy2 defined field like this:-

from app import db
from app.mixins import TimestampMixin
from geoalchemy2 import Geometry

class Event(db.Model, TimestampMixin):
    __tablename__ = 'events'

    id = db.Column(db.BigInteger, primary_key=True)
    title = db.Column(db.Unicode(255))
    start = db.Column(db.DateTime(timezone=True))
    location = db.Column(Geometry(geometry_type='POINT', srid=4326))
    is_active = db.Column(db.Boolean(), default=False)

    def __repr__(self):
        return '<Event %r %r>' % (self.id, self.title)

Attempting to save an event object with the event.location assigned with the above json value fails with this error

DataError: (DataError) Geometry SRID (0) does not match column SRID (4326)

What's the correct format event.location has to be in order for the

db.session.add(event)
db.session.commit() 

to work correctly?


Solution

  • It was an error in the way I process my geojson. I need to explicitly state the srid that the geojson has to conform to.

    This is the solution:-

    def process_formdata(self, valuelist):
        """ Convert GeoJSON to DB object """
        if valuelist:
            geo_ob = geojson.loads(valuelist[0])
            # Convert the Feature into a Shapely geometry and then to GeoAlchemy2 object
            # We could do something with the properties of the Feature here...
            self.data = from_shape(asShape(geo_ob.geometry), srid=4326)
        else:
            self.data = None