将变量(非模型字段)传递给Django rest框架中的序列化器

时间:2018-10-02 12:03:27

标签: python django python-3.x django-rest-framework postman

我在序列化器中添加了一个非模型字段,但是在点击api后,它将字段返回为None值,它不存储要在序列化器函数中使用的值

serializers.py

class LeaveTeamSerializer(serializers.ModelSerializer):
    user_id = serializers.SerializerMethodField()

    class Meta:
        model = Team
        fields = ['id', 'name', 'user_id', 'players']

    def get_user_id(self, *args, **kwargs):
        user_id = None  # kwargs['context']['request'].user_id
        return user_id # user_id it's not who did the request it is other user_id

    def update(self, instance, validated_data):
        user_id = validated_data.get('user_id')
        user = self.context['request'].user

        if user_id is None or user_id == '':
            instance.players.remove(user)
        else:
            instance.players.remove(user_id)
        instance.save()
        return instance

views.py

class LeaveTeamListAPIView(RetrieveUpdateAPIView):
    queryset = Team.objects.all()
    serializer_class = LeaveTeamSerializer

    def get_queryset(self):
        return Team.objects.filter(players=self.request.user) and Team.objects.filter(admin=self.request.user)

json放置请求

{
    "user_id":"22",
    "name":"a"
}

我需要的是从json请求中检索到user_id(不是执行请求的用户,而是其他user_id)值,如上述json代码到序列化器类,以便在if语句中使用它。

请任何人有解决方案帮助我 我试图克服这种情况,但对我来说效果不佳

谢谢

修改

`class LeaveTeamSerializer(serializers.ModelSerializer):
    user_id = serializers.CharField(write_only=True)

    class Meta:
        model = Team
        fields = ['id', 'name', 'user_id', 'players']

    def update(self, instance, validated_data):
        user_id = self.user_id
        print(user_id)        
        user = self.context['request'].user

        if user_id is None or user_id == '':
            instance.players.remove(user)
        else:
            instance.players.remove(user_id)
        instance.save()
        return instance

`

1 个答案:

答案 0 :(得分:2)

使用 serializers.CharField() 代替 serializers.SerializerMethodField() ,并将 write_only=True 标记为

class LeaveTeamSerializer(serializers.ModelSerializer):
    user_id = serializers.CharField(write_only=True)
    # .... your code


注意:请不要忘记从当前代码段中删除 get_user_id() 方法