【问题标题】:Why can't I PATCH Django REST Framework PrimaryKeyRelatedField to empty list?为什么我不能将 Django REST Framework PrimaryKeyRelatedField 修补为空列表?
【发布时间】:2019-12-09 21:19:21
【问题描述】:

我在 Django REST 框架中遇到了一个奇怪的问题。我正在尝试使用 PATCH 请求向/从用户添加和删除组。

我可以修补到/api/users/:id/ 以更新最初为空的groups 列表。例如,以下操作会产生这些结果:

  1. PATCH /api/users/:id/ {"groups": [1]} -> 结果用户为groups: [1]
  2. PATCH /api/users/:id/ {"groups": [1, 2]} -> 结果用户为groups: [1,2]
  3. PATCH /api/users/:id/ {"groups": [1]} -> 用户返回groups: [1]

所以我成功地使用 PATCH 请求更新了状态。但是以下内容未能相应更新:

PATCH /api/users/:id/ {"groups": []} -> 用户仍在groups: [1]

这是我的 UserSerializer 类:

class UserSerializer(serializers.ModelSerializer):
    groups = serializers.PrimaryKeyRelatedField(many=True,
                                                queryset=Group.objects.all(),
                                                allow_empty=True, required=False)

    class Meta:
        model = User
        fields = (
            'id',
            'username', 'first_name', 'last_name', 'is_staff', 'is_authenticated', 'is_superuser', 'email',
            'groups'
        )

我怀疑它与 PrimaryKeyRelatedField 有关 - 我尝试了构造函数的许多参数组合但无济于事。

【问题讨论】:

  • 我尝试使用您的序列化程序配置,不幸的是我无法重现该问题,这意味着,无论我放置与groups 字段相对应的任何数组,它都只是覆盖。
  • 这是来自@Martini991,但他没有评论所需的声誉:I've the same issue: the problem is that when you pass an empty list, the PATCH method recognise it like there is "no field" provided. Being so, the strategy for no field is to leave it untouched. You can change the HTTP method to UPDATE and give the whole object to the server again to work-around the problem, but of course is not a solution.
  • 正如@JPG 提到的,我已经尝试过这个相同的 sn-p 序列化程序,并且得到了预期的结果。
  • Python、Django 和 DRF 的版本是什么? @c_sagan
  • Python 3.8、Django 3.0.6、DRF 3.11.0

标签: python django django-rest-framework


【解决方案1】:

这实际上是由于 UserViewSet 中的 partial_update 覆盖中的错误

修复此问题后,PATCH 按预期工作,使用默认 partial_update Django REST Framework 提供的用户不应遇到此问题。

【讨论】:

    猜你喜欢
    • 2016-07-03
    • 2016-10-31
    • 2019-03-11
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多