下面是我的urls.py,我需要指定有效负载的结构并在每个请求中指定标头
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register("patient", views.PatientsApiView)
urlpatterns = [
url(r'', include(router.urls))
]
以下是我的观点。py 我使用模型viewset制作了一个视图,使用通用API视图制作了另一个视图
class PatientsApiView(viewsets.ModelViewSet):
model = Patient
fields = ("id", "first_name", "last_name", "phone", "email", "created_at")
"""
Create a serializer in serializer.py
class EmbryoSerializer(serializers.ModelSerializer):
class Meta:
model = Embryo
fields = ("id", "name", "analysis_result", "created_at", "patient")
"""
class EmbryoApiView(APIView):
def get(self, request, format=None):
embryo = Embryo.objects.all()
serializer = EmbryoSerializer(embryo, many=True)
return Response(serializer.data)
def post(self, request, format=None):
serializer = EmbryoSerializer(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)
def put(self, request, pk, format=None):
embryo = self.get_object(pk)
serializer = EmbryoSerializer(embryo, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def patch(self, request, user_id):
user = User.objects.get(id=user_id)
serializer = EmbryoSerializer(embryo, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
router.register("embryo", views.EmbroApiView)
您认为我如何在views.py中实现这一目标
答案 0 :(得分:0)
最好在views.py和serializers.py
中为每个请求指定有效负载和标头的结构有效载荷将在序列化器中验证。您可以简单地将标头传递给Response()。
例如
return Response( … , headers={'My-Header': 'hello'})
将添加标题。
示例:
class EmbryoApiView(APIView):
def get(self, request, format=None):
embryo = Embryo.objects.all()
serializer = EmbryoSerializer(embryo, many=True)
return Response(serializer.data, headers={'My-Header': 'Below are all the embroys for this patient'})