【问题标题】:Django Rest, How to update a single field of the object in viewset? I get IntegrityError for the required fieldsDjango Rest,如何更新视图集中对象的单个字段?我得到必填字段的 IntegrityError
【发布时间】:2021-07-16 00:17:44
【问题描述】:

现在我有一个大目录对象,并且有一个请求,我想修改它的一个字段。(其余部分保持不变)。我有必填字段,所以当我执行 PATCH 请求时出现此错误。

null value in column "team_id" of relation "Catalogs_catalog" violates not-null constraint
DETAIL:  Failing row contains (ecf8ede4-1438-441b-8e45-152658512d27, null, [], {}, [], Europe/Moscow, t, null, ["a@a.com"]).

我将视图集用于目录视图,并向其添加了一个额外的操作,以便我可以发送一个 PATCH 请求来更新该字段。

Views.py

    @action(methods=['patch'], detail=True, url_path='add_to_whitelist', url_name='add_to_whitelist')
    def add_to_whitelist(self, request, pk=None):
        catalog = self.get_object()
        users_to_add = request.data
        serializer = WhiteListUpdateSerializer(data=users_to_add,  partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response({"message": "Saved the new white list."}, 201)
        return Response({"message":"Error creating white list.", "error": serializer.errors}, 400)

Serializers.py

class WhiteListUpdateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Catalog
        fields = ('whitelist_users',)

partial=True 或重写 partial_update 不起作用。我是 DRF 的新手,我在这里缺少什么?

【问题讨论】:

    标签: django django-rest-framework django-rest-viewsets


    【解决方案1】:

    改变

    WhiteListUpdateSerializer(data=users_to_add,  partial=True)
    

    WhiteListUpdateSerializer(catalog, data=users_to_add,  partial=True)
    

    【讨论】:

      猜你喜欢
      • 2013-11-12
      • 1970-01-01
      • 2016-09-18
      • 1970-01-01
      • 1970-01-01
      • 2015-07-15
      • 2021-04-04
      • 2021-11-20
      • 2023-04-05
      相关资源
      最近更新 更多