Django REST Framework NOT NULL 约束失败

当我尝试通过发布以下 JSON 来创建新帖子时:


{

    "text": "test",

     "location": 1

}

我收到以下错误:


NOT NULL constraint failed: grapevineapp_post.location_id

模型.py:


class Location(models.Model):

    name = models.CharField(max_length=80)

    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):

        return self.name


class Post(models.Model):

    text = models.CharField(max_length=512)

    owner = models.ForeignKey('auth.User', related_name='posts', on_delete=models.CASCADE)

    location = models.ForeignKey(Location, related_name='posts', on_delete=models.CASCADE)

    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):

        return self.text

视图.py:


class PostList(generics.ListCreateAPIView):

    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

    queryset = Post.objects.all()

    serializer_class = PostSerializer

    def perform_create(self, serializer):

        serializer.save(owner=self.request.user)


class PostDetail(generics.RetrieveUpdateDestroyAPIView):

    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

    queryset = Post.objects.all()

    serializer_class = PostSerializer

序列化器.py


class PostSerializer(serializers.Serializer):

    id = serializers.IntegerField(read_only=True)

    text = serializers.CharField(required=False, allow_blank=True, max_length=512)

    owner = serializers.ReadOnlyField(source='owner.username')

    location = serializers.PrimaryKeyRelatedField(many=False, read_only=True)


    def create(self, validated_data):

        return Post.objects.create(**validated_data)


    def update(self, instance, validated_data):

        instance.text = validated_data.get('text', instance.text)

        instance.location = validated_data.get('location', instance.location)

        instance.save()

        return instance


DB 已经被清除。位置已通过使用管理界面创建。我知道这个问题是微不足道的,但我无法让它发挥作用。


千巷猫影
浏览 158回答 1
1回答

慕神8447489

为了详细说明 Willem Van Onsem 所说的内容,您将PostSerializer.location字段设置为read-only. 您为其提供的 json 数据将被忽略(文档),即它不会包含在您的validated_data.然后,当您调用Post.objects.create(**validated_data)您的create方法时,它会尝试创建一个Post没有位置参数的实例,并且您会收到错误消息。编辑:在您对查询集发表评论之后。您需要为它提供一个查询集来验证(文档)。在你的情况下你想要location = serializers.PrimaryKeyRelatedField(    many=False,    queryset=Location.objects.all())
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python