我的前端(Angular2)将JSON发布到我的Django Rest Framework后端。我很困惑我的序列化程序应该如何处理JSON并提取信息。我的ContactFormSerializer
如何提取JSON data['userDetails']['email']
?
# Posted data example:
{
"sessionID": "1",
"created": "2/12/2016",
"completed": false,
"payment": {
...
},
"userDetails": {
"userID": 1,
"email": "foo@gmail.com",
"location": "US"
}
}
class ContactUsView(APIView):
def post(self, request):
serializer = ContactFormSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class ContactFormSerializer(serializers.Serializer):
def save(self):
# How can I grab the user email address from the JSON?
# send email to us
答案 0 :(得分:0)
如果要为ContactFormSerializer编写自定义保存方法。 也许它会有所帮助
def save(self,validated_data):
user_details = validated_data.pop('userDetails')
model = Model.objects.create(
userID = user_details['userID'],
email = user_details['email'],
location = user_details['location']
)
model.save()