custom URLs using django rest framework

后端 未结 2 851
执念已碎
执念已碎 2021-02-06 10:16

I am trying to use the django rest framework to expose my models as APIs.

serializers

class UserSerializer(serializers.HyperlinkedModelS         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-06 10:56

    I was able to get this to work by using the approach posted here.

    django-rest-framework HyperlinkedIdentityField with multiple lookup args

    The second error I was receiving was becuase I was including the url definition inside the meta section. It should be before the meta section instead. I also had to specify the lookup field in the viewset code. Here are the relevant parts of my code.

    urls.py

    from user.views import UserViewSet
    user_list = UserViewSet.as_view({'get':'list'})
    user_detail = UserViewSet.as_view({'get':'retrieve'})
    
    urlpatterns= [
        url(r'^users/$', user_list, name='user-list'),
        url(r'^user/(?P\d+)/(?P[-\w\d]+)/$', user_detail, name='user-detail'),
        url(r'^api-auth/', include('rest_framework.urls',namespace = 'rest_framework'))
    ]
    

    views.py:

    class UserViewSet(viewsets.ModelViewSet):
        """
        API end point for user details and user list
        """
        lookup_field = 'id'
        serializer_class = UserSerializer
        queryset = user.objects.all()
    

    serializers.py

    class UserSerializer(serializers.HyperlinkedModelSerializer):
        url = ParameterisedHyperlinkedIdentityField(view_name='user-detail', lookup_fields=(('id', 'id'), ('slug', 'slug')), read_only=True)
    
        class Meta:
            model = user
            fields = ('url','name','cover_photo')
    

提交回复
热议问题