[英]Serialize geometry using flask-marshmallow
I have a sqlalchemy2 (with geoalchemy extension) model containing geometry data type like so:我有一个包含几何数据类型的sqlalchemy2(带有geoalchemy扩展)model,如下所示:
class Estate(db.Model):
id = db.Column(db.Integer, primary_key=True)
geom = db.Column(Geometry(geometry_type='POLYGON')
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
user = db.relationship('Users', backref='estates')
and the marshmallow schema:和棉花糖模式:
class EstateSchema(ma.ModelSchema):
class Meta:
model = Estates
but during attempt of serialization I received following error:但在尝试序列化期间,我收到以下错误:
marshmallow_sqlalchemy.exceptions.ModelConversionError: Could not find field column of type <class 'geoalchemy2.types.Geometry'>.
The ModelConversion
complaining about WKBElement
, because is not defined as a common field. ModelConversion
抱怨WKBElement
,因为未定义为公共字段。
Question is, how can I modify the code, to get the (de)serializer working with Geometry model field?问题是,如何修改代码,以使(反)序列化器与 Geometry model 字段一起工作?
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, fields
from geoalchemy2.shape import to_shape
from common.models import Node
class 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.这会将
Geometry
字段返回为 Shapely shape 字段,类似于我正在寻找的POINT (39.2934324 -123.59348)
。
marshmallow_sqlalchemy
do not know how to serialize the field geom
of type Geometry
. marshmallow_sqlalchemy
不知道如何序列化Geometry
类型的字段geom
。 This is because GeoAlchemy
is not directly supported in marshmallow
.这是因为在
marshmallow
中不直接支持GeoAlchemy
。 In order to solve this you need to write a custom ModelConverter
which tells marshmallow
how to serialize a field of type Geometry
.为了解决这个问题,您需要编写一个自定义
ModelConverter
来告诉marshmallow
如何序列化Geometry
类型的字段。
from geoalchemy2.types import Geometry as GeometryType
from marshmallow_sqlchemy.convert import ModelConverter as BaseModelConverter
class 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在marshmallow- sqlalchemy 的 github 存储库中也提到了相同的内容
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.