8

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 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This answer helped me a ton! I know it's been a while since you posted it, but do you have any idea if it's possible to register these separately bound (is that the right word?) views with the router, so that they can be seen in the browsable API?
@dkhaupt You can mark extra actions for routing as per here: django-rest-framework.org/api-guide/viewsets/… — I'm not sure that gives you what you need. Ultimately you may need to override the template for browsable API and add whatever link you need. (The view itself can be rendered as with any other.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.