我是DRF的新手,正在尝试构建rest API,我将模型,URL,视图和序列化器设置为:
model.py:
//a[contains(text(),'nnn jhjhjk')]/parent::*/preceding-sibling::*/child::*
来自urls.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)
来自apiview.py:
from django.urls import path, include
# from .routers import router
from . import apiview
app_name = 'deployments'
urlpatterns = [
# path('', include(router.urls), name='deployments'),
path('deployments/', apiview.DeploymentsList.as_view(), name='deployment-list'),
path('deployments/<int:pk>/', apiview.DeploymentDetail.as_view(), name='deployment_detail')
]
来自serializers.py:
class DeploymentDetail(generics.RetrieveUpdateDestroyAPIView):
def retrieve(self, request, *args, **kwargs):
pk = self.kwargs.get('pk')
return Response(DeploymentOnUserModel.objects.get(pk=kwargs['pk']))
当我尝试访问:http://127.0.0.1:8000/api/v1/deployments/?pk=1/时,它应该返回单个对象 id = 1 ,但它返回所有对象。
答案 0 :(得分:2)
应该将pk作为GET参数的一部分传递给pk,而不是像这样:
http://127.0.0.1:8000/api/v1/deployments/1/
您正尝试使用由http://127.0.0.1:8000/api/v1/deployments/?pk=1/
执行的DeploymentsList
的URL,因为它不包含pk
url kwarg。
此外,您还应该序列化对象,然后将其作为响应返回:
class DeploymentDetail(generics.RetrieveUpdateDestroyAPIView):
def retrieve(self, request, *args, **kwargs):
pk = self.kwargs.get('pk')
object = DeploymentOnUserModel.objects.get(pk=kwargs['pk'])
serializer = DeploymentOnUserSerializer(object)
return Response(serializer.data)
答案 1 :(得分:0)
当我尝试使用get方法而不是检索url错误时,但是 它返回另一个错误为:类型为“ DeploymentOnUserModel”的对象为 无法JSON可序列化
我知道已经很晚了,但是在您的apiview.py
中class DeploymentDetail(generics.RetrieveUpdateDestroyAPIView):
serializer_class = DeploymentOnUserSerializer()
def get_queryset(self):
pk = self.request.GET.get("pk")
return deployment = DeploymentOnUserModel.objects.get(pk=pk)