view.py
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from .models import PatientDetail
from .serializer import PatientSerializer
import sqlite3
# Create your views here.
@api_view(['Get', 'POST'])
# @csrf_exempt
def patient_list(request):
if request.method == 'GET':
data = request.data
patientname = data['patientName']
# patientnric = data['patientNRIC']
patientdetails = PatientDetail.objects.filter(patientName = patientname )
# patientdetails = PatientDetail.objects.all()
# serialization
serializer = PatientSerializer(patientdetails, many=True)
# return Json
return Response(serializer.data)
elif request.method == 'POST':
#data = JSONParser().parse(request)
serializer = PatientSerializer(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)
@api_view(['Get', 'PUT','DELETE'])
@csrf_exempt
def patient_detail(request,patientNRIC):
try:
patientdetails = PatientDetail.objects.get(patientNRIC = patientNRIC)
except PatientDetail.DoesNotExist:
return HttpResponse(status=404)
if request.method == "GET":
# serialization, getting one data only
serializer = PatientSerializer(patientdetails)
# return Json
return JsonResponse(serializer.data)
elif request.method == "PUT":
data = JSONParser().parse(request)
serializer = PatientSerializer(patientdetails, data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=400)
elif request.method == 'DELETE':
patientdetails.delete()
return HttpResponse(status=204)
模型.py
from django.db import models
from django.db import models
class PatientDetail(models.Model):
patientName = models.CharField(max_length=100)
patientNRIC = models.CharField(max_length=100, primary_key=True)
patientAddress = models.CharField(max_length=100)
patientAllergies = models.CharField(max_length=100)
patientMedicationName = models.CharField(max_length=100)
dosage = models.CharField(max_length=100)
sideEffects = models.CharField(max_length=100)
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.patientName
答案 0 :(得分:0)
正如错误所述,您没有在请求正文中传递任何请求数据,因此 KeyError
已被触发。
request.data
使用 POST
方法发送数据时会有数据,由于您使用的是 GET
方法,因此您的请求正文将为空。此外,如果您使用 GET
方法(如 <url-endpoint>/?patientName=John
)并使用 request.query_params['patientName']
获取数据,则应使用参数传递数据。