1

我是 DRF 的新手,正在尝试构建一个 rest API,我已将模型、URL、视图和序列化程序设置为:

模型.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)

来自 urls.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')

]

来自 apiview.py:

class DeploymentDetail(generics.RetrieveUpdateDestroyAPIView):

    def retrieve(self, request, *args, **kwargs):
        pk = self.kwargs.get('pk')

        return Response(DeploymentOnUserModel.objects.get(pk=kwargs['pk']))

来自 serializers.py:

class DeploymentOnUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = DeploymentOnUserModel
        fields = '__all__'

当我尝试访问时:http: //127.0.0.1 :8000/api/v1/deployments/?pk=1/它应该返回一个id=1的对象,但它会返回所有对象。

4

2 回答 2

4

与其将 pk 作为 GET 参数传递,不如将其作为 url 的一部分传递,如下所示:

http://127.0.0.1:8000/api/v1/deployments/1/ 

您尝试使用http://127.0.0.1:8000/api/v1/deployments/?pk=1/的URLDeploymentsList不包含pkurl 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)
于 2018-06-28T06:34:14.093 回答
0

当我尝试获取方法而不是检索时,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) 
于 2020-03-24T00:27:49.750 回答