无法更新JSON字段。显示" JSON解析错误 - 期望用双引号括起来的属性名称"

时间:2016-06-21 11:14:31

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

我是Django Rest Framework的新手。我目前正在制作一个API,它将获得最喜爱的电视节目,并创建或更新现有列表,如果更多的电视节目是最喜欢的。所有这些都有一个唯一的account_id。我必须发送这样的JSON响应。

{
  "account_id": "15",
  "shows": [
    {
      "show_id": "19"
    },
    {
      "show_id": "86"
    }
  ]
}

但是当我试图推出这样的JSON响应时,

{
    "account_id": 15,
    "shows": [
    {
        "show_id": "9"
    },
    {
        "show_id": "86"
    }
    ]
}

我收到了错误,

{
  "detail": "JSON parse error - Expecting property name enclosed in double quotes: line 2 column 5 (char 6)"
}

我的models.py是:

from django.db import models


class Account(models.Model):
    account_id = models.CharField(max_length=500)


class Show(models.Model):
    show_id = models.CharField(max_length=500)
    user_id = models.ForeignKey(Account, related_name='shows')

我的views.py是:

from .models import Show, Account
from showapp.serializers import ShowSerializer, AccountSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view


class UserList(APIView):

    parser_classes = (JSONParser,)

    def get(self, request, format=None):
        users = Account.objects.all()
        serializer = AccountSerializer(users, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = AccountSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        user = self.get_object(pk)
        user.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

@api_view(['GET', 'PUT'])
def user_detail(request, account_id):

    try:
        user = Account.objects.get(account_id=account_id)
    except Account.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = AccountSerializer(user)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = AccountSerializer(user, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

我的serializers.py是:

class ShowSerializer(serializers.ModelSerializer):

    class Meta:
        model = Show
        fields = ('show_id',)


class AccountSerializer(serializers.ModelSerializer):

    shows = ShowSerializer(many=True)

    class Meta:
        model = Account
        fields = ('account_id', 'shows')

请帮帮我。

0 个答案:

没有答案