django-rest-framework and custom routes

2019-08-08 10:33发布

问题:

I have the following setup.

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

Then in my urlpatterns

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

Then in my views.py

 class PostViewSet(viewsets.ModelViewSet):

Now that works perfectly for my use case but I also want to do something like this to grab data from a certain day

/api/post/2013/08/09/

That would pull out all the data for that current day.. I'm a bit unsure how to do custom routes in django-rest

回答1:

The part of the Django Rest Framework docs you're looking for is that on filtering against the URL.

The basic idea is that you override get_queryset to return a filtered QuerySet matching parameters you define in your URL conf.

The Django ORM field lookups you'll need are year, month and day, which start here in the QuerySet API reference.

I hope that helps.