问题描述
有什么方法可以将GeoDjango的POINTFEILD序列化为JSON?
我有以下型号
class Company(models.Model):
name = models.CharField(max_length=200,default='Company',null=True)
def __unicode__(self):
return self.name
class Shop(models.Model):
name = models.CharField(max_length=200,default="bla")
address = models.CharField(max_length=300,default='blabla')
location = models.PointField(null=True,blank=True,geography=True)
company = models.ForeignKey(
Company,on_delete=models.CASCADE,null=True)
以及后续的序列化器
class ShopSerializer(serializers.ModelSerializer):
distance = serializers.DecimalField(
source='distance.km',max_digits=10,decimal_places=2,required=False,read_only=True)
# serialize('geojson',Shop.objects.all(),# geometry_field='location',fields=('name','address'))
class Meta:
model = Shop
fields = ['id','name','address','location','distance']
class CompanySerializer(serializers.ModelSerializer):
shop_set = ShopSerializer(many=True)
class Meta:
model = Company
fields = ['id','shop_set']
def create(self,validated_data):
shop_validated_data = validated_data.pop('shop_set')
company = Company.objects.create(**validated_data)
shop_set_serializer = self.fields['shop_set']
for each in shop_validated_data:
each['company'] = company
shops = shop_set_serializer.create(shop_validated_data)
return company
使用GeoJson我可以得到如下响应
[
{
"id": 1,"name": "Cosmetica","address": "somwhere","location": {
"type": "Point","coordinates": [
24.896,67.182
]
}
},
,但这里的point字段已转换为数组。但是我需要它是具有2个键值对的Json对象,
location:{lat,long}
任何人都可以帮忙
解决方法
您为什么不使用geos API? https://docs.djangoproject.com/en/3.1/ref/contrib/gis/geos/#django.contrib.gis.geos.GEOSGeometry.coords
pnt.coords