JSONField序列化为POST的json,但是GET的字符串

时间:2017-11-09 15:09:44

标签: python json django django-models django-rest-framework

我的代码可能存在一个非常简单的问题,但是我已经在几天内对这个问题大打折扣,并且无法取得任何进展。

重要套餐:

Django==1.11.3
django-cors-headers==2.1.0
djangorestframework==3.7.0
drf-nested-routers==0.90.0
psycopg2==2.7.3
pycparser==2.18

以下是发生的事情:

我通过AJAX调用创建模型

enter image description here

我的服务器正确地将 brainstorm_data 字段序列化为json对象。

现在我将用户导航到下一页并获取当前模型

enter image description here

出于某种原因, brainstorm_data 现在以字符串形式返回。无论何时我在这个资源上调用GET请求,我总是得到一个JSON对象的字符串表示。

以下是相关代码:

models.py

from django.contrib.postgres.fields import JSONField

class Adventure(TimeStampedModel,
                    models.Model):
        name = models.CharField(max_length=200)
        user = models.ForeignKey(User)
        world = models.ForeignKey(World)
        theme = models.ForeignKey(Theme, default=1)
        brainstorm_data = JSONField()
        image_src = models.CharField(max_length=400, null=True, blank=True)
        sentence_summary = models.TextField(null=True, blank=True)
        paragraph_summary = models.TextField(null=True, blank=True)
        page_summary = models.TextField(null=True, blank=True)
        outline_complete = models.BooleanField(default=False)
        brainstorm_complete = models.BooleanField(default=False)
        private = models.BooleanField(default=False)

        def __str__(self):
            return self.name

views.py

class MyAdventuresViewSet(viewsets.ModelViewSet):
    queryset = Adventure.objects.all()
    serializer_class = AdventureSerializer
    permission_classes = (permissions.IsAuthenticated,)

    def get_queryset(self):
        return Adventure.objects.filter(user=self.request.user)

    def create(self, request, *args, **kwargs):
        user = self.request.user
        world = World.objects.filter(user=user).first()

        if not world:
            world = World.objects.create(name='My World', user=user,
                                         description="This is a default world we created for your adventures",
                                         image_src=static('worlds/images/world_placeholder.png'))

        data = request.data.copy()
        data['user'] = user.pk
        data['world'] = world.pk
        data['theme'] = 1  # default theme
        data['brainstorm_data'] = default_brainstorm
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        adventure = serializer.save()

        Storyboard.objects.create(adventure=adventure, raw=default_storyboard['raw'], html=default_storyboard['html'])

        return JsonResponse(serializer.data)

    @detail_route(methods=['post'])
    def complete_outline(self, request, pk):
        adventure = Adventure.objects.get(pk=self.kwargs['pk'])
        complete_adventure_outline(adventure)

        serializer = self.get_serializer(data=adventure)
        serializer.is_valid(raise_exception=True)
        return JsonResponse(serializer.data, status=200)

    @detail_route(methods=['post'])
    def genres(self, request, pk):
        genre_names = request.data
        genre_models = Genre.objects.filter(name__in=genre_names)
        adventure = self.get_object()
        adventure.genre_set.set(genre_models)
        adventure.save()
        serializer = AdventureSerializer(adventure)
        return JsonResponse(serializer.data)

serializers.py

class AdventureSerializer(serializers.ModelSerializer):
    genre_set = serializers.StringRelatedField(many=True, read_only=True)
    character_set = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    location_set = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    storyboard = serializers.PrimaryKeyRelatedField(read_only=True)
    theme = serializers.PrimaryKeyRelatedField(queryset=Theme.objects.all())

    class Meta:
        model = Adventure
        fields = '__all__'

混入

# this is a dictionary used to default brainstorm data each time an adventure is created
default_brainstorm = {
    "nodes": [...],
    "edges": [...]
}

2 个答案:

答案 0 :(得分:4)

您可以覆盖新序列化程序字段中的to_internal_valueto_representation来处理JSON字段的返回数据。

class JSONSerializerField(serializers.Field):
    """Serializer for JSONField -- required to make field writable"""

    def to_internal_value(self, data):
        return data

    def to_representation(self, value):
        return value

反过来,您可以在序列化程序中使用此字段:

class SomeSerializer(serializers.ModelSerializer):
    json_field = JSONSerializerField()

    class Meta:
        model = SomeModelClass
        fields = ('json_field', )

这可以解决你的问题:)

答案 1 :(得分:0)

当我最初创建列时,我使用不同的json字段包。基本数据库列实际上是文本而不是 json jsonb 。创建新列(django json字段),迁移数据,然后移回数据使我的数据库以一致的顺序返回。