如何在对象的JSON字段中创建数组?

时间:2018-08-15 16:03:24

标签: python django django-rest-framework

出现了这样的问题。我可以传递一个JSON格式的对象

[
 {
"title": "test",
"address": "55.99752311227003,49.08959250252893"
 },
 {
"title": "test122",
"address": "63.08891623673952,46.243883499999946"
 },
 {
"title": "test1111",
"address": "55.69684742706125,37.59635133512744"
 },
 {
"title": "kgeu",
"address": "55.816852257889856,49.09529045886616"
 }
]

但是我需要获取JSON对象格式

[ 
 {
"title": "kgeu",
"address": [55.816852257889856,49.09529045886616]
 }
]

setting.py

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ),
     'DEFAULT_PARSER_CLASSES': (
        'rest_framework.parsers.JSONParser',
    )
}

serializers.py

class FactorySerializer(serializers.ModelSerializer):

    class Meta:
        model = Factory
        fields = ['title', 'address']

views.py

class FactoryListView(generics.ListCreateAPIView):
    queryset = Factory.objects.all()
    serializer_class = FactorySerializer

该怎么做? 预先感谢您的帮助

3 个答案:

答案 0 :(得分:0)

检索侧将使用什么堆栈?

无论如何,由于您已将坐标存储为字符串,因此Django应该如何知道您希望它返回具有经度和纬度的列表? 您可以执行以下操作:

替代1:

使用PostgreSQL和一个列表字段。那会返回您想要的。

替代2:

编写一个返回列表的方法,Django Rest可以读取该方法。 在您的models.py模型中看起来像这样:

@property
def get_coordinates_formatted(self):
    coordinates = self.address.split(sep=",")
    return [coordinates[0], coordinates[1]]

然后将其添加到您的serializer.py:

address = serializers.Field(source='model.get_coordinates_formatted')

答案 1 :(得分:0)

首先将以下内容导入您的models.py文件中:

from django.contrib.postgres.fields import JSONField

创建模型字段时,可以将其设置为:

my_JSON_field = JSONField(default='')

然后在序列化器中包括:

class FactorySerializer(serializers.ModelSerializer):

    my_JSON_field = serializers.JSONField()

    class Meta:
        model = Factory
        fields = ['my_JSON_field']

因此,当您导航到可浏览的api时,您将通过以下方式进行RAW DATA Post请求设置:

{
 "my_JSON_field": {
        "title": "kgeu",
        "address": [55.816852257889856,49.09529045886616]
    }
}

答案 2 :(得分:0)

您只需要这样做:

class FactorySerializer(serializers.ModelSerializer):

    class Meta:
        model = Factory
        fields = ['title', 'address']

    def to_representation(self, instance):
        """split address."""
        ret = super().to_representation(instance)
        ret['address'] = ret['address'].split(',')
        return ret