REST urls with tastypie
I'm using tastypie in my django application and I'm trying to get it to 开发者_如何学Cmap urls like "/api/booking/2011/01/01" which maps to a Booking model with the specified timestamp in the url. The documentation falls short of telling how to achieve this.
What you want to do in your Resource is provide an
def prepend_urls(self):
return [
url(r"^(?P<resource_name>%s)/(?P<year>[\d]{4})/(?P<month>{1,2})/(?<day>[\d]{1,2})%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('dispatch_list_with_date'), name="api_dispatch_list_with_date"),
]
method, which returns a url, which points to a view (I named it dispatch_list_with_date) that does what you want.
For example, in the base_urls class, it points to a view called 'dispatch_list' that's the primary entry point for listing a resource, and you'll probably just want to sort of replicate that with your own filtering.
Your view might look pretty similar to this
def dispatch_list_with_date(self, request, resource_name, year, month, day):
# dispatch_list accepts kwargs (model_date_field should be replaced) which
# then get passed as filters, eventually, to obj_get_list, it's all in this file
# https://github.com/toastdriven/django-tastypie/blob/master/tastypie/resources.py
return dispatch_list(self, request, resource_name, model_date_field="%s-%s-%s" % year, month, day)
Really I would probably just add a filter to the normal list resource
GET /api/booking/?model_date_field=2011-01-01
You can get this by adding a filtering attribute to your Meta class
But that's a personal preference.
精彩评论