【问题标题】:django rest framework ModelSerializer post data errordjango rest框架ModelSerializer发布数据错误
【发布时间】:2013-11-07 09:36:44
【问题描述】:

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

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

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

【问题讨论】:

  • UserCommentSerializer 使用user = serializers.PrimaryKeyRelatedField(read_only=True)
  • @hcwhsa 我试过了,然后我得到了IntegrityError: (1048, "Column 'user_id' cannot be null") 错误。
  • 尝试通过:{"user":"1", "rate":"5", "description":"hello"}
  • @hcwhsa 谢谢。我尝试在UserCommentSerializer 中使用user = serializers.PrimaryKeyRelatedField()。有用。但当我从http://127.0.0.1:8000/apps/usercomments/ 获取数据时,我没有得到{"user":1,"rate":5,"description":"hello world"} 我想以{"user":{"id":1,"username":"watsy"},"rate":5,"description":"hello world"} 获取数据@>_
  • 好的,然后在UserCommentSerializer序列化器中添加depth = 1。您应该在 Meta 类中添加此字段。 django-rest-framework.org/api-guide/…

标签: python django django-rest-framework


【解决方案1】:

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

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

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

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

【讨论】:

  • 如果我用户 read_only=True,当我传递 json 时,我得到了 IntegrityError: (1048, "Column 'user_id' cannot be null") 我添加了 depth=1,但我得到的 json 数据与没有它时相同。
猜你喜欢
  • 2014-09-21
  • 2016-05-03
  • 2013-10-05
  • 2015-05-15
  • 2019-03-24
  • 2017-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多