REST网址与tastypie

sw0*_*w00 5 django rest tastypie

我在我的django应用程序中使用tastypie并且我试图将它映射到像"/ api/booking/2011/01/01"这样的URL,它映射到具有URL中指定时间戳的Booking模型.文档没有说明如何实现这一目标.

Iss*_*lly 12

您想要在您的资源中做什么是提供

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"),
    ]
Run Code Online (Sandbox Code Playgroud)

方法,它返回一个url,它指向一个你想要的视图(我命名为dispatch_list_with_date).

例如,在base_urls类中,它指向一个名为"dispatch_list"的视图,它是列出资源的主要入口点,您可能只想对使用自己的过滤进行复制.

您的视图可能与此非常相似

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)
Run Code Online (Sandbox Code Playgroud)

真的,我可能只是在普通列表资源中添加一个过滤器

GET /api/booking/?model_date_field=2011-01-01
Run Code Online (Sandbox Code Playgroud)

您可以通过向Meta类添加过滤属性来实现此目的

但这是个人偏好.