我是 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的对象,但它会返回所有对象。