【问题标题】:Optional pk argument for CREATE in Django's DRF ModelViewSetDjango 的 DRF ModelViewSet 中 CREATE 的可选 pk 参数
【发布时间】:2018-11-22 14:30:08
【问题描述】:

我的一个模型有一个常规的 ModelViewSet,但我希望可以选择指定一个特定的 PK 来创建一个新实例。例如。如果我要发帖:

{
    "name": "Name"
}

它会得到一个随机的pk。但如果我发帖:

{
    "id": "123",
    "name": "Name"
}

我希望它具有指定的 pk (id)。

类似于this 人,我所做的是将id 字段添加到我的 ModelSerializer 中,如下所示:

class ConversationViewSet(viewsets.ModelViewSet):
    """
    List all conversations, or create new / edit existing product.
    """
    queryset = Conversation.objects.all()
    serializer_class = ConversationSerializer

class ConversationSerializer(serializers.ModelSerializer):
    id = serializers.CharField(required=False)  # Instead of serializer.ReadOnlyField()

    class Meta:
        model = Conversation
        fields = '__all__'

虽然这适用于create 方法,但它会导致updatepartial_update 的问题,其中id 现在是作为查询字符串参数的必需参数,并且在请求正文中像这样(来自文档):

update
PUT /conversations/{id}/
Update existing conversation.

Path Parameters
The following parameters should be included in the URL path.

Parameter       Description
id (required)   A unique value identifying this conversation.

Request Body
The request body should be a "application/json" encoded object, containing the following items.

Parameter       Description
id  
access_token    
username    
password    
app_user_id 
name    

当然,有两个同名的参数是不好的做法。例如。当使用requests 并传递参数字典时,它不再起作用,因为它不知道我正在处理哪个参数。

我该如何解决这个问题,以使 id 参数仅对 create 方法是可选的,而所有其他方法(列表、读取、...)与默认情况下完全相同?

我的解决方案

根据 JPG 的回答,我将序列化器修改为:

class ConversationSerializer(serializers.ModelSerializer):
    id = serializers.ReadOnlyField()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.context['view'].action == 'create':
            self.fields['id'] = serializers.CharField(required=False)

    class Meta:
        model = Conversation
        fields = '__all__'

【问题讨论】:

  • Views 使用的是哪个类?模型视图集?
  • 是的,模型视图集。在上面添加了我的视图

标签: django django-rest-framework


【解决方案1】:

我认为这可以通过重写序列化程序的 __init__() 方法来实现。

class ConversationSerializer(serializers.ModelSerializer):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.context['view'].action == 'create':
            self.fields['id'] = serializers.CharField()
        else:
            self.fields['id'] = serializer.ReadOnlyField()

    class Meta:
        model = Conversation
        fields = '__all__'

【讨论】:

  • 太棒了,谢谢!我稍微调整了您的解决方案,但这有效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-02
  • 1970-01-01
  • 2020-03-02
  • 2017-11-16
  • 1970-01-01
  • 2017-08-03
  • 2021-10-13
相关资源
最近更新 更多