django-rest-framework反序列化使用用户外键创建对象的请求

时间:2016-02-01 08:16:20

标签: python django rest django-rest-framework

我想创建一个带有外键SpiderService的{​​{1}}。

模型:

request.user

串行器:

from django.contrib.auth.models import User

class SpiderService(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=20)

的观点:

class SpiderServiceSerializer(serializers.ModelSerializer):
    user = serializers.ReadOnlyField(source='user.id')

    class Meta:
        model = SpiderService
        fields = ('id', 'user', 'name') 

class SpiderServiceListSerializer(viewsets.ModelViewSet):
    queryset = SpiderService.objects.all()
    serializer_class = SpiderService

发布时

class SpiderServiceList(APIView):

    def get(self, request, format=None):
        services = SpiderService.objects.all()
        serializer = SpiderServiceSerializer(services, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = SpiderServiceSerializer(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 perform_create(elf, serializer):
        serializer.save(user=self.request.user)

到api url,得到500错误:

{
    "name": "2"
}

我已阅读Serializer relations,发现我不应该像上面那样编写代码。官方示例等同于删除[01/Feb/2016 15:39:55] "POST /services/ HTTP/1.1" 500 17105 IntegrityError: NOT NULL constraint failed: spmanage_spiderservice.user_id 中的user field,并将SpiderServiceSerializer添加到spiderservice field。似乎旨在实现django模型中UserSerializer的语法,这不符合我的目的。

我只想用user.spiderservice_set创建一个spiderservice对象。

如何解决?

2 个答案:

答案 0 :(得分:2)

您需要将当前用户添加为extra parameter to the Serializer's save method

serializer.save(user=request.user)

答案 1 :(得分:0)

你有用户模型的任何帐户序列化器吗? 如果是这样,请在您的SpiderServiceSerializer中尝试:

user = AccountSerializer(read_only=True, required=False)