如何在django REST框架中修改request.data
我正在使用Django REST框架
request.data = '{"id": "10", "user": "tom"}'
我想添加额外的属性,如"age": "30"
然后再发送它
request.data = new_data
response = super().post(request, *args, **kwargs)
我有两个问题
它看起来像一个JSON字符串。 要将其转换为字典,您应该这样做:
import json
data = json.loads(request.data)
那么你可以添加额外的属性:
data['age'] = 30
那么你将不得不提出新的要求,因为它看起来像你不能改变旧的。 这假设您发布到/ notes /:
from rest_framework.test import APIRequestFactory
factory = APIRequestFactory()
request = factory.post('/notes/', data, format='json')
一位好朋友刚刚以比我上面说明的更简单的方法带我去上学
class CreateSomething(CreateAPIView):
model = Something
queryset = Something.objects.all()
serializer_class = SomethingSerializer
perform_create(self,serializer):
def perform_create(self,serializer):
ip = self.get_ip()
## magic here: add kwargs for extra fields to write to db
serializer.save(ip_addr=ip)
def get_ip(self):
x_forwarded_for = self.request.META.get('HTTP_X_FORWARDED_FOR',None)
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = self.request.META.get('REMOTE_ADDR',None)
return ip
class SomethingSerializer(serializers.ModelSerializer):
email = serializers.EmailField(validators=[UniqueValidator(queryset=Something.objects.all())])
fieldA = serializers.CharField()
fieldB = serializers.CharField()
class Meta:
model = Customer2
fields = ['email','fieldA','fieldB','ip_addr']
read_only_fields = ['ip_addr']
根据你的评论:
“因为在发布之前,我需要修改API所需的字段名称aqs”
您应该使用Field
的source
参数。
这将使错误消息更加一致,否则您的用户将面临他们没有提供的字段名称的错误。
链接地址: http://www.djcxy.com/p/30477.html上一篇: How can modify request.data in django REST framework
下一篇: Android in App billing test purchase crashes Play store