简体   繁体   English

django-rest-framework:如何序列化已经包含JSON的字段?

[英]django-rest-framework: How Do I Serialize a Field That Already Contains JSON?

I am pretty new to the django-rest-framework, so could use some help. 我是django-rest-framework的新手,所以可以使用一些帮助。

I have an object with a TextField that is a string containing JSON. 我有一个TextField的对象,它是一个包含JSON的字符串。

I'm using django-rest-framework to serialize the whole object as JSON. 我正在使用django-rest-framework将整个对象序列化为JSON。 However, this one string that is already JSON gets serialized as an encoded string containing the JSON rather than the JSON itself. 但是,这个已经是JSON的字符串被序列化为包含JSON而不是JSON本身的编码字符串。

How can I tell the serializer to send this field as-is rather than trying to transform this string to JSON? 如何告诉序列化器按原样发送此字段而不是尝试将此字符串转换为JSON? Is there some sort of "ignore" decorator or override I can use? 我可以使用某种“忽略”装饰器或覆盖吗? Or can I pre-parse this JSON before serializing? 或者我可以在序列化之前预先解析这个JSON吗?

This is the difference between having: 这是有以下区别:

{"data": data}

and

{"data": "data"}

The latter being more of a nuisance to use on the client side... 后者在客户端使用起来更麻烦......

I solved this another way: 我解决了另一种方式:

1: use a JSON-Field for the JSON content ( django-jsonfield or django-json-field should be fine). 1:对JSON内容使用JSON-Field( django-jsonfielddjango-json-field应该没问题)。 These then will to loads/dumps as needed 然后根据需要加载/转储

2: in my serializer, use the transform-method to prevent the data added as string to the response 2:在我的序列化程序中,使用transform-method来防止数据作为字符串添加到响应中

class MyModelSerializer(serializers.ModelSerializer):
    def transform_myjsonfield(self, obj, value):
        return obj.myjsonfield

    class Meta:
        model = MyModel

If you need write-access, you only have to add a method validate_myjsonfield which converts back. 如果您需要写访问权限,则只需添加一个返回的方法validate_myjsonfield

(of course, this could be also done with a custom DRF serializer field. (当然,这也可以通过自定义DRF序列化器字段完成。

You can simply decode the json into python object: 您可以简单地将json解码为python对象:

json_obj = json.loads(model.json_text)

Once you serialize your object, replace this field with the decoded object: 序列化对象后,将此字段替换为已解码的对象:

data = serializer.data
data["field"] = json_obj
return Response(data)

Here is what works for me on, djangorestframework==3.9.1 : 这对我djangorestframework==3.9.1djangorestframework==3.9.1

import json

from rest_framework import serializers

from .models import WeatherLocation


class WeatherLocationSerializer(serializers.ModelSerializer):
    LocationId = serializers.CharField(source='location_id')
    City = serializers.CharField(source='city')
    Region = serializers.CharField(source='region')
    Name = serializers.CharField(source='name')
    Country = serializers.CharField(source='country')
    WeatherForecastLongTermTimePeriods = serializers.JSONField(required=False, allow_null=True,
                                                               source='weather_forecast_long_term_time_periods')
    WeatherForecastShortTermTimePeriods = serializers.JSONField(required=False, allow_null=True,
                                                                source='weather_forecast_short_term_time_periods')

    def to_representation(self, instance):
        ret = super(WeatherLocationSerializer, self).to_representation(instance)
        ret['WeatherForecastLongTermTimePeriods'] = json.loads(ret['WeatherForecastLongTermTimePeriods'])
        ret['WeatherForecastShortTermTimePeriods'] = json.loads(ret['WeatherForecastShortTermTimePeriods'])
        return ret

    class Meta:
        model = WeatherLocation
        fields = ['LocationId', 'City', 'Region', 'Name', 'Country',
                  'WeatherForecastLongTermTimePeriods', 'WeatherForecastShortTermTimePeriods', ]

I thought there would be an easier way to do this, but by changing the behaviour of to_representation , I can convert my text fields to JSON. 我认为有一种更简单的方法可以做到这一点,但通过改变to_representation的行为,我可以将我的文本字段转换为JSON。 For reference, here is my models.py : 作为参考,这是我的models.py

from django.db import models


class WeatherLocation(models.Model):
    """
    Weather app schema, from southparc
    """
    location_id = models.CharField(primary_key=True, null=False, blank=False, default=None, max_length=254,
                                   editable=True)
    region = models.CharField(max_length=2, null=False, blank=False)
    city = models.CharField(null=False, blank=False, max_length=254)
    province = models.CharField(null=True, blank=True, max_length=254)
    name = models.CharField(null=True, blank=True, max_length=254)
    country = models.CharField(null=True, blank=True, max_length=254)

    # JSON fields
    weather_forecast_long_term_time_periods = models.TextField(default="", blank=True)
    weather_forecast_short_term_time_periods = models.TextField(default="", blank=True)

    # Dates
    created_date = models.DateTimeField(auto_now_add=True)
    modified_date = models.DateTimeField(auto_now=True)

Hope that helps. 希望有所帮助。 If you use a JSONField that is supported by Postgres, I'm sure you won't need to do this. 如果你使用Postgres支持的JSONField ,我相信你不需要这样做。 I'm using a TextField to save my JSON here. 我正在使用TextField来保存我的JSON。 I thought that specifying the field type as serializers.JSONField on the serializer would be enough but its not the case. 我认为在字符串serializers.JSONField上将字段类型指定为serializers.JSONField就足够了,但事实并非如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 django-rest-framework 将嵌套的 m2m 字段序列化为 self ? - How can I serialize a nested m2m field to self with django-rest-framework? 如何将OneToOneField序列化为Django-Rest-Framework中的列表? - How can I serialize the OneToOneField to be list in Django-Rest-Framework? 使用django-rest-framework将模型对象序列化为JSON dict - Serialize model objects into a JSON dict using django-rest-framework 如何使用django-rest-framework创建Login视图 - How do I create a Login view with django-rest-framework 如何使用 Django-Rest-Framework 序列化用户组 - How to serialize groups of a user with Django-Rest-Framework django-rest-framework:如何序列化数据库模型的连接? - django-rest-framework: How to serialize join of database models? 如何在 django-rest-framework 的序列化器中使用时区序列化时间? - how to serialize time with timezone in django-rest-framework's serializer? 如何在Django-rest-framework中序列化具有自定义关系的2个模型? - How to serialize 2 models with custom relationship in django-rest-framework? 如何使用django-rest-framework序列化ValuesQuerySet? - How to serialize a ValuesQuerySet using django-rest-framework? Django-Rest-Framework-如何反序列化自定义嵌套字段 - Django-Rest-Framework - How to Deserialize Custom Nested Field
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM