将PointField转换为JSON对象

问题描述 投票:0回答:1

有什么方法可以将GeoDjango的POINTFIELD序列化为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', 'name', '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": "somewhere",
        "location": {
            "type": "Point",
            "coordinates": [
                24.896,
                67.182
            ]
        }
    },

但是这里点字段已经转换成数组了。但我需要它是带有 2 个键值对的 Json 对象

location:{lat,long}

有人可以帮忙吗

json geojson geodjango
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.