Serialize geometry using flask-marshmallow
I know this is pretty old, but answering now as I just solved this for myself after landing on this question. The way I accomplished it is just by adding a method field to my schema like so:
from marshmallow_sqlalchemy import SQLAlchemySchema, fieldsfrom geoalchemy2.shape import to_shapefrom common.models import Nodeclass NodeSchema(SQLAlchemySchema): class Meta: model = Node geom = fields.fields.Method("geomToPoint") def geomToPoint(self, obj): return to_shape(obj.geom)
This returns the Geometry
field as a Shapely shape field, something like POINT (39.2934324 -123.59348)
which is what I was looking for.
marshmallow_sqlalchemy
do not know how to serialize the field geom
of type Geometry
. This is because GeoAlchemy
is not directly supported in marshmallow
. In order to solve this you need to write a custom ModelConverter
which tells marshmallow
how to serialize a field of type Geometry
.
from geoalchemy2.types import Geometry as GeometryTypefrom marshmallow_sqlchemy.convert import ModelConverter as BaseModelConverterclass ModelConverter(BaseModelConverter): SQLA_TYPE_MAPPING = { **BaseModelConverter.SQLA_TYPE_MAPPING, **{GeometryType: fields.Field()}, }class EstateSchema(ma.ModelSchema): class Meta: model = Estates model_converter = ModelConverter
The same has been mentioned in the github repository of marshmallow-sqlalchemy