如何在对象的JSON字段生成数组?

2024-06-16 08:34:28 发布

您现在位置:Python中文网/ 问答频道 /正文

有这样一个问题。我可以传递一个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对象格式

^{pr2}$

在设置.py在

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

在序列化程序.py在

class FactorySerializer(serializers.ModelSerializer):

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

在视图.py在

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

怎么做? 提前谢谢你的帮助


Tags: 对象pytestrestjsondefaulttitleaddress
3条回答

你只需要这样做:

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

检索端将使用哪个堆栈?在

总之,既然您已经将坐标存储为一个字符串,Django应该如何知道您希望它返回一个带有纬度和经度的列表? 你可以做的是:

备选方案1:

使用PostgreSQL和列表字段。这会得到你想要的。在

备选方案2:

编写一个方法,返回一个列表,Django Rest可以读取。 这看起来像你的模型.py型号:

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

然后把这个加到你的序列化程序.py公司名称:

^{pr2}$

首先在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时,您将按照以下方式设置原始数据发送请求:

^{pr2}$

相关问题 更多 >