django-rest custom url in a ModelViewSet

2019-02-12 21:51发布

I'm having an issue adding a custom URL to a ModelViewSet in django-rest-framework. Here's an example of my main urls.py

router = routers.DefaultRouter()
router.register(r'post', PostViewSet)

urlpatterns = patterns('',
    url(r'^api/', include(router.urls)),
)

My modelviewset looks like

class PostViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = Post.objects.all()
    serializer_class = PostSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)
    search_fields = ('created')

    def pre_save(self, obj):
        obj.user = self.request.user


    #
    # based on the post type this will decide which serializer to use for the data
    def get_serializer_class(self):
        #
        # default is the Text role serializer
        return PostSerializer

That works great for a url like

 /api/post/

I'm looking to get a set day like

/api/post/yyyy/mm/dd/

Or should I just use something like

/api/post/?year=&month=&day=

1条回答
We Are One
2楼-- · 2019-02-12 22:38

Pull the list method out as a separate view:

post_list = PostViewSet.as_view({'get': 'list'})

Then map this to your date-based lookup URL as you usually would, setting parameters for year, month and day.

In get_queryset you can check if these kwargs are set and, if so, filter the queryset.

查看更多
登录 后发表回答