如何在Django Rest Framework序列化程序中访问使用POST请求发送的额外数据

时间:2017-10-30 12:38:06

标签: python django django-rest-framework

我正在尝试使用POST请求发送一个额外的数组来创建一个组。

POST /groups/
{
  "name": “New Group“,
  "users_to_invite": [ 1, 2, 6 ]
}

我正在使用Django Rest Framework的{​​{1}}来处理请求:

ListCreateAPIView

我想在序列化程序中找到class GroupListView(ListCreateAPIView): queryset = Group.objects.all() def get_serializer(self, *args, **kwargs): kwargs['context'] = self.get_serializer_context() # Use a dedicated serializer to inspect the field with users to invite if self.request.method == 'POST': return GroupCreateSerializer(*args, **kwargs) return GroupSerializer(*args, **kwargs) 数组的内容来创建邀请对象。但是,我无法这样做,因为当我在序列化程序中访问它时,数组不存在。

users_to_invite

阵列不存在,所以我自然会收到错误:

class GroupCreateSerializer(ModelSerializer):

    def create(self, validated_data):
        # Get user ids to invite
        # !! It fails here !!
        invitations_data = validated_data.pop('users_to_invite')

        # TODO: Iterate over ids and create invitations

        # Create a group
        group = Group.objects.create(**validated_data)
        return group

    class Meta:
        model = Group
        fields = ('id', 'name', )

如何让数组出现在那里?修改模型听起来不是一个好主意,因为我不想存储数组中的内容。

3 个答案:

答案 0 :(得分:1)

validated_data您可以尝试使用self.context['request']个详细信息including-extra-context,默认情况下会在get_serializer视图方法中添加

适用于您的情况:

def create(self, validated_data):
    # Get user ids to invite
    # !! It fails here !!
    request = self.context['request']
    invitations_data = request.data.get('users_to_invite')

答案 1 :(得分:1)

要发送额外的上下文数据,您应该从方法def get_serializer_context(self)传递它,并访问序列化程序,如self.context.get("key")

示例代码:

class GroupListView(ListCreateAPIView):
    queryset = Group.objects.all()

    def get_serializer_context(self):
        context = super(GroupListView, self).get_serializer_context()
        context["users_to_invite"] = request.data.get("users_to_invite")
        return context

class GroupCreateSerializer(ModelSerializer):

    def create(self, validated_data):
        users_to_invite = self.context.get("users_to_invite")
        # do whatever you want

参考:https://micropyramid.com/blog/django-rest-framework-send-extra-context-data-to-serializers/

答案 2 :(得分:0)

除了将数据添加到上下文之外,您还可以将字段users_to_invite作为CharField添加到序列化程序。

示例

import json

class GroupCreateSerializer(ModelSerializer):

    def create(self, validated_data):
        # Get user ids to invite
        # !! It fails here !!
        invitations_data = json.loads(validated_data.pop('users_to_invite'))

        # TODO: Iterate over ids and create invitations

        # Create a group
        group = Group.objects.create(**validated_data)
        return group

    users_to_invite = serializers.CharField(required=False)

    class Meta:
        model = Group
        fields = ('id', 'name', 'users_to_invite', )

注意:确保将请求数据中的users_to_invite作为字符串。喜欢:'[1, 2, 3]'