django rest框架ModelSerializer发布数据错误

时间:2013-11-07 09:36:44

标签: python django django-rest-framework

首先,在 models.py

class UserComment(models.Model):
    user = models.ForeignKey(User)
    rate = models.IntegerField()
    description = models.CharField(max_length=512)
    createTime = models.DateTimeField(auto_now=True)
    def __unicode__(self):
        return '<UserComment {%s %d}>' % (self.user.username, self.rate)

然后, serializers.py

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'email', )

class UserCommentSerializer(serializers.ModelSerializer):
    user = UserSerializer(required=False)
    class Meta:
        model = UserComment

views.py

class UserCommentViewSet(viewsets.ModelViewSet):
    queryset = UserComment.objects.all()
    serializer_class = UserCommentSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly, )

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.DATA, files=request.FILES)
        serializer.is_valid()
        print serializer.errors
        print serializer.data
        return super(UserCommentViewSet, self).create(request, *args, **kwargs)

然后我发布json数据 {"user":{"id":"1","username":"watsy"},"rate":"5","description":"hello"}

我认为,它会起作用。并将其插入db,但我收到错误。

{"user": [{"username": ["User with this Username already exists."]}]}
&gt; _&lt; ,我不知道。

1 个答案:

答案 0 :(得分:1)

您需要对序列化程序进行一些更改:

class UserCommentSerializer(serializers.ModelSerializer):
    user = serializers.PrimaryKeyRelatedField(read_only=True)
    class Meta:
        model = UserComment
        depth = 1

现在在您的请求中传递此JSON dict:

{"user":"1", "rate":"5", "description":"hello"}