【问题标题】:IntegrityError, (1048, "Column 'category_owner_id' cannot be null") in Django REST with axios带有 axios 的 Django REST 中的 IntegrityError,(1048,“列 'category_owner_id' 不能为空”)
【发布时间】:2018-09-24 01:58:51
【问题描述】:

我想通过 axios 将服务器的数据发布到前端, 但我不断面临错误:

/profile/ 处的完整性错误 (1048, "列 'category_owner_id' 不能为空")

我在后端使用 DRF,在前端使用 React。这是我的 React 和 DRF 部分。

getCategory.js

axios({
        url: 'http://127.0.0.1:8000/profile/',
        method: 'POST',
        data: { 
            data: this.state.information,
        },
        contentType: 'application/json',
     })
     .then(res => {
         console.log(res);
     })
     .catch(err => {
         console.log(err);
     })

Serializer.py

class CategorySerializer(serializers.HyperlinkedModelSerializer):  
    class Meta:
        model = Category
        fields = ('id', 'category_name', 'category_owner_id', 'parentId')

views.py

class SettingView(viewsets.ModelViewSet) :
    queryset = models.Category.objects.all()
    serializer_class = CategorySerializer

    def get(self, request) :
        return JsonResponse(context)

    def post(self, request, format=None):
        return Response("ok")

当然,我赶紧查进去http://127.0.0.1:8000/profile/

如果category_owner_id列有空值,但没有一个是空的..

enter image description here

我是 django REST Framework 的新手,所以您的所有帮助对我来说都很棒!

【问题讨论】:

  • 异常表明,您没有将 category_owner_id 从反应应用程序传递给 DRF
  • @JPG 谢谢回复,你的意思是如果我想通过HTTP获取'category_owner_id'值,我必须先发布相同的值?
  • 没有。在发出 HTTP POST 请求时,您正在向 Django API 发送一些数据。在该数据中,不包括 category_owner_id
  • @JPG 那么,我是否将category_owner_id的值放入data(axios的参数)?
  • 我不确定反应方面。但是你应该尝试类似的方法

标签: django reactjs post django-rest-framework axios


【解决方案1】:

使用 ModelSerializer 代替 HyperlinkedModelSerializer 可能会有所帮助

class CategorySerializer(serializers.ModelSerializer):  
    class Meta:
        model = Category
        fields = ('id', 'category_name', 'category_owner_id', 'parentId')

此外,如果您将深度设置为 1,它会导致相同的问题,您可以删除并尝试

# depth = 1

【讨论】:

    猜你喜欢
    • 2016-09-06
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 2022-12-12
    相关资源
    最近更新 更多