Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django-rest custom url in a ModelViewSet

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=
like image 687
Mike Avatar asked Aug 12 '13 18:08

Mike


1 Answers

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.

like image 187
Carlton Gibson Avatar answered Oct 20 '22 06:10

Carlton Gibson