【问题标题】:IntegrityError at /api/img/ null value in column "author_id" violates not-null constraint“author_id”列中 /api/img/ 空值的 IntegrityError 违反了非空约束
【发布时间】:2020-08-20 19:11:03
【问题描述】:

django rest 框架发布请求错误 这是图像模型

class Img(models.Model):
    created_at=models.DateTimeField(auto_now_add=True)
    author=models.ForeignKey(User,on_delete=models.CASCADE,related_name="img")
    picture=models.ImageField(upload_to='fake_picture',null=True,blank=True)
    tags = TaggableManager(blank=True)

这是模型 Img 的图像序列化器

class ImgSerializer(serializers.ModelSerializer):
    tags = TagListSerializerField(required=False)
    author = serializers.StringRelatedField(read_only=True)
    # post   = serializers.StringRelatedField(read_only=True)
    class Meta:
        model=Img
        fields='__all__'

views.py

class ImgViewSet(viewsets.ModelViewSet):
    parser_class = (FileUploadParser,)
    permission_classes =[IsAuthenticatedOrReadOnly,IsAuthorOrReadOnly]
    authentication_classes =(TokenAuthentication,JSONWebTokenAuthentication)
    queryset = Img.objects.all()
    serializer_class=ImgSerializer

但是,当 post man 触发对特定 api 端点的 post 请求时,键值对为

picture:image.jpg

这就是回应

IntegrityError at /api/img/
null value in column "author_id" violates not-null constraint
DETAIL:  Failing row contains (4, fake_picture/2019-06-27_at_10-04-59.png, 2020-05-05 23:06:00.16071+00, null).


Request Method: POST
Request URL: http://localhost:8000/api/img/

【问题讨论】:

  • 您已在序列化程序的作者字段上设置了 read_only,但该字段在您的模型上是必需的。保存模型前需要设置字段
  • 考虑到你的观点我已经删除了 read_only=True 仍然有错误

标签: django django-models django-rest-framework django-authentication django-serializer


【解决方案1】:

请试试这个

class ImgViewSet(viewsets.ModelViewSet):
    ..........
    serializer_class=ImgSerializer
    .......
    def perform_create(self, serializer):
       serializer.save(author=serializer.context['request'].user)

【讨论】:

    猜你喜欢
    • 2021-01-21
    • 2013-05-12
    • 1970-01-01
    • 1970-01-01
    • 2016-10-21
    • 2016-01-18
    • 2019-04-08
    • 2017-10-15
    • 1970-01-01
    相关资源
    最近更新 更多