我正在使用Django和restframework-json-api软件包开发REST API。 我提出以下要求
const sortedlocations = locations.sort((a, b) => a.distance - b.distance);
this.setState({locations: sortedlocations});
我得到这个答复
curl --location --request POST 'http://localhost:8000/api/students/' \
--header 'Content-Type: application/json' \
--data-raw '{
"data": {
"type": "students",
"attributes": {
"first_name": "First Name",
"last_name": "Last Name"
}
}
}'
这是我的代码: models.py
{
"errors": [
{
"detail": "This field is required.",
"status": "400",
"source": {
"pointer": "/data/attributes/first_name"
},
"code": "required"
}
]
}
serializers.py
class Student(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
views.py
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = ('first_name',)
urls.py
class StudentsViewSet(viewsets.ModelViewSet):
queryset = Student.objects.all()
parser_classes = (JSONParser, FormParser, MultiPartParser)
serializer_class = StudentSerializer
settings.py
router = routers.DefaultRouter()
router.register(r'students', views.StudentsViewSet, 'student')
urlpatterns = [
path('', views.index, name='index'),
path('api/', include(router.urls))
]
如果我改为不使用JSONParser并使用常规的django请求格式而不是Json API,则可以正常工作。我想念什么?
答案 0 :(得分:0)
您使用的解析器与DRF的“解析器”部分中引用的推荐JSONParser不同: https://www.django-rest-framework.org/api-guide/parsers/
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
]
}