我创建了一个序列化器来发布结果,但是当我尝试使用邮递员时,它说值'enrollment_id'为空:
views.py
case 3:
System.out.println("Encontrar um curso");
idCurso = sq.nextInt();
findCurso(idCurso);
break;
serializers.py
from rest_framework import generics
from .serializers import ResponseSerializer
class ResponseCreate(generics.CreateAPIView):
serializer_class = ResponseSerializer
urls.py
class ResponseSerializer(serializers.ModelSerializer):
class Meta:
model = Response
fields = (
'enrollment_id',
'evaluation_id',
'question_id',
'question_component_id',
'user_id',
)
在邮递员的邮件正文中,我发送以下json:
from django.urls import path
from . import views
urlpatterns = [
path('', views.ResponseCreate.as_view()),
]
错误邮递员:
{
"enrollment_id": 1,
"user_id": 2,
"question_component_id": 2,
"question_id": 1,
"evaluation_id": 1
}
视图
编辑:
模型响应:
IntegrityError at /response/
null value in column "enrollment_id" violates not-null constraint
DETAIL: Failing row contains (9, null, null, null, null, null).
答案 0 :(得分:0)
您必须在网址格式中指明将允许使用的方法:
urlpatterns = [
path('', views.ResponseCreate.as_view({'get': 'list'})),
]
我可以从错误中看到您得到`GET方法是不允许的,这是因为您没有指示Django允许它。
尝试此视图:
from rest_framework import viewsets
from .serializers import ResponseSerializer
class ResponseCreate(viewsets.ModelViewSet):
queryset = models.Response.objects.all()
serializer_class = serializers.ResponseSerializer
ModelViewSet 已经对所有方法都具有正确的响应,但是您必须在url模式中指出允许哪些方法。
答案 1 :(得分:0)
编辑: 您的串行不用添加模型字段后“_id”。 应该是这样的:
class ResponseSerializer(serializers.ModelSerializer):
class Meta:
model = Response
fields = (
'enrollment',
'evaluation',
'question',
'question_component',
'user',
)
现在尝试经由邮差seding改性JSON:
{
"enrollment": 1,
"user": 2,
"question_component": 2,
"question": 1,
"evaluation": 1
}
您需要在视图中定义一个queryset
:
class ResponseCreate(generics.CreateAPIView):
queryset = Response.objects.all()
serializer_class = ResponseSerializer