1

I'm looking for how to make a GET in django swagger framework by refClient (a unique CharField in my client's model). I found on the internet that I have to customize the routers, I have that as routers :

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')),
   ] 

But I got this error

ValueError: invalid literal for int() with base 10: 'refClient'
[21/Jul/2017 15:25:22] "GET /swagger/ HTTP/1.1" 500 133494

Should I add something to my serializers's configuration

class ClientSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Client
        fields = ('refClient', 'nom', 'prenom')

Or to my views ?

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)

Basically how I can customize my swagger ?

4

1 回答 1

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')

于 2017-07-22T05:50:11.923 回答