1

首先,在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

视图.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"}

我想,它会起作用的。并将其插入数据库,但我得到错误。

{"user": [{"username": ["User with this Username already exists."]}]}
>_<,我不知道。

4

1 回答 1

1

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

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

现在在您的请求中传递这个 JSON 字典:

{"user":"1", "rate":"5", "description":"hello"}
于 2013-11-08T11:16:06.800 回答