我正在寻找如何通过refClient(我客户端模型中的一个独特的CharField)在django swagger框架中进行GET。 我在互联网上发现我必须自定义路由器,我将其作为路由器:
from rest_framework.schemas import get_schema_view
from rest_framework_swagger.renderers import SwaggerUIRenderer, OpenAPIRenderer
schema_view = get_schema_view(
title='Swagger documentation',
renderer_classes = [OpenAPIRenderer, SwaggerUIRenderer],
)
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter(trailing_slash=False)
router.register(r'clients/{refClient}', ClientViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
url(r'^admin/', admin.site.urls),
# To show the swagger documentation
url(r'^swagger/', schema_view, name="docs"),
url(r'^api/v1/', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
但是我收到了这个错误
ValueError: invalid literal for int() with base 10: 'refClient'
[21/Jul/2017 15:25:22] "GET /swagger/ HTTP/1.1" 500 133494
我应该在序列化程序的配置中添加一些内容
class ClientSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Client
fields = ('refClient', 'nom', 'prenom')
或者我的观点?
class ClientViewSet(viewsets.ModelViewSet):
queryset = Client.objects.all()
serializer_class = ClientSerializer
def get_queryset(self):
""" GET : get all clients """
return Client.objects.all()
def create(self, request):
""" POST : Create a Client object """
return super(ClientViewSet, self).create(request)
def retrieve(self, request, pk=None):
""" GET : Returns a single client item """
return super(ClientViewSet, self).retrieve(request, pk)
def update(self, request, *args, **kwargs):
""" PUT : Updates a single client item """
return super(ClientViewSet, self).update(request, *args, **kwargs)
def partial_update(self, request, *args, **kwargs):
""" PATCH : Partiel update a client """
return super(ClientViewSet, self).partial_update(request, *args, **kwargs)
def destroy(self, request, pk=None):
""" DELETE : Delete a client """
return super(ClientViewSet, self).destroy(request, pk)
基本上我如何定制我的招摇?
答案 0 :(得分:1)
默认情况下,django rest框架使用此方法
lookup_field = 'pk'
lookup_url_kwarg = None
您可以在ClientViewSet类中覆盖它,更改为
lookup_field = 'refClient'
但是如果你想通过'pk'或'refClient'来支持这两种查找,我建议为后一个查找一个不同的端点(例如/ api / client_url / ref /),或者添加过滤选项你的列表视图(例如/ api / client_url?refClient ='something')