我是 DRF 的新手,正在尝试构建一个 rest api,我需要为任务执行创建一个 api,而不仅仅是为 CRUD,这就是为什么我将 APIView 的 POST 方法覆盖为:
class DeploymentsList(viewsets.ModelViewSet):
queryset = DeploymentOnUserModel.objects.all()
serializer_class = DeploymentonUserSerializer
def create(self, request, *args, **kwargs):
"""overwrite this for extra actions"""
serializer = self.serializer_class(data=request.data)
if serializer.is_valid(raise_exception=True):
print('valid request')
serializer.save()
return Response(serializer.data)
else:
print('Something invalid')
return Response('Invalid request')
模型.py:
services = (
('Single', 'Single'),
('Multiple', 'Multiple'),
)
class DeploymentOnUserModel(models.Model):
deployment_name = models.CharField(max_length=256, )
credentials = models.TextField(blank=False)
project_name = models.CharField(max_length=150, blank=False)
project_id = models.CharField(max_length=150, blank=True)
cluster_name = models.CharField(max_length=256, blank=False)
zone_region = models.CharField(max_length=150, blank=False)
services = models.CharField(max_length=150, choices=services)
configuration = models.TextField()
routing = models.TextField()
def save(self, **kwargs):
if not self.id and self.services == 'Multiple' and not self.routing and not self.configuration:
raise ValidationError("You must have to provide routing for multiple services deployment.")
super().save(**kwargs)
序列化程序.py:
class DeploymentonUserSerializer(serializers.ModelSerializer):
model = DeploymentOnUserModel
fields = '__all__'
readonly_fields = 'pk'
网址.py:
app_name = 'deployments'
urlpatterns = [
path('deployments/', apiview.DeploymentsList.as_view({'get': 'list', 'post': 'create'}), name='deployment_list'),
path('deployments/<int:pk>', apiview.DeploymentDetail.as_view(), name='deployment_detail')
]
错误返回:
AttributeError:“str”对象没有属性“values”
更新:完整追溯
Internal Server Error: /api/v1/deployments/
Traceback (most recent call last):
File "/Users/abdul/KontainerApi/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/Users/abdul/KontainerApi/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/abdul/KontainerApi/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/abdul/KontainerApi/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/abdul/KontainerApi/lib/python3.6/site-packages/rest_framework/viewsets.py", line 95, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/abdul/KontainerApi/lib/python3.6/site-packages/rest_framework/views.py", line 494, in dispatch
response = self.handle_exception(exc)
File "/Users/abdul/KontainerApi/lib/python3.6/site-packages/rest_framework/views.py", line 454, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/abdul/KontainerApi/lib/python3.6/site-packages/rest_framework/views.py", line 491, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/abdul/PycharmProjects/KontainerApi/deployments/apiview.py", line 15, in create
serializer.is_valid(raise_exception=False)
File "/Users/abdul/KontainerApi/lib/python3.6/site-packages/rest_framework/serializers.py", line 236, in is_valid
self._validated_data = self.run_validation(self.initial_data)
File "/Users/abdul/KontainerApi/lib/python3.6/site-packages/rest_framework/serializers.py", line 435, in run_validation
value = self.to_internal_value(data)
File "/Users/abdul/KontainerApi/lib/python3.6/site-packages/rest_framework/serializers.py", line 459, in to_internal_value
fields = self._writable_fields
File "/Users/abdul/KontainerApi/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Users/abdul/KontainerApi/lib/python3.6/site-packages/rest_framework/serializers.py", line 370, in _writable_fields
field for field in self.fields.values()
AttributeError: 'str' object has no attribute 'values'
[27/Jun/2018 16:11:41] "POST /api/v1/deployments/ HTTP/1.1" 500 15073
但我不知道如何验证请求?当我覆盖 APIView 的 POST 方法时。
发布数据:
{
"deployment_name": "dep5",
"credentials": "cre4",
"project_name": "pro4",
"project_id": "004",
"cluster_name": "clus4",
"zone_region": "zon4",
"services": "Single",
"configuration": "conf4",
"routing": "route4"
}