Django:如何在不渲染反斜杠的情况下序列化模型的文本字段

时间:2018-11-19 19:38:29

标签: python django api django-rest-framework

我有一个这样的模型:

SELECT count(*) as Anzahl, MONTHNAME( date ) AS Monat, YEAR( date ) AS Jahr, 
branch as Branch, ordered as Ordered FROM wccrm_anprobe where status = 1 GROUP 
BY MONTHNAME(date), 
YEAR(date), branch, ordered ORDER BY date,branch ASC

字段class Activity(models.Model): date_added = models.DateTimeField(auto_now_add=True) start_date = models.DateTimeField(default=datetime.datetime.now) data = models.TextField() # stores activity's JSON in text format, not as Python object number = models.IntegerField(default=0) athlete = models.ForeignKey(Athlete, on_delete=models.CASCADE, default=None) 将JSON 存储为文本

我正在为此模型使用以下序列化器:

data

现在,当我在Django shell中执行以下操作时:

from rest_framework import serializers
from .models import Activity


class ActivitySerializer(serializers.ModelSerializer):

    class Meta:
        model = Activity
        fields = ("date_added", "start_date", "data", "number", "athlete")

生成的输出很好:

>>>from explorer_api.models import Activity
>>>fromt explorer_api.serializers import ActivitySerializer
>>>activity = Activity.objects.latest('id')
>>>serializer = ActivitySerializer(activity)
>>>serializer.data

但是,当我尝试使用JSON渲染器时:

>>> serializer.data
{'date_added': '2018-11-19T21:10:29.324522Z', 'start_date': '2018-11-15T05:36:10Z', 'athlete': 1, 'data': '{"resource_state":3,"athlete":{"id":3255732,"resource_state":1},"name":"Morning Ride","distance":33605.0,"moving_time":5067,"elapsed_time":5067,"total_elevation_gain":59.0,

>>>from rest_framework.renderers import JSONrenderer >>>JSONRenderer.render(serializer.data) 用反斜杠转义以逃避双qoutes:

activity.data

如何防止这种情况?我希望我的API公开纯JSON文本。

1 个答案:

答案 0 :(得分:1)

您可以覆盖serializers.Field以创建新的SerilizerField并更改其behavior。例如:

import json

class JSONSerializerField(serializers.Field):

    def to_representation(self, obj):
        try:
            return json.loads(obj)
        except (ValueError, Exception) as e:
            # log exception
            return obj

    def to_internal_value(self, data):
        return data

class ActivitySerializer(serializers.HyperlinkedModelSerializer):
    data = JSONSerializerField()

    class Meta:
        model = Activity
        fields = ('data', 'id', 'date_added', 'start_date')