我正在尝试按以下方式构建API:
api/v1/<client_slug>/track/expenses
但是,我真的没有任何需要在/clients
返回的数据,至少在这一点上,所以我希望避免创建一个遵循REST标准的ClientResource。下面是我的ExpenseResource的一个例子。
class ExpenseResource(ModelResource):
class Meta:
resource_name = 'expenses'
queryset = Expense.objects.all() # Wish to filter by client_slug
include_resource_uri = False
authentication = OAuthTokenAuthentication()
authorization = Authorization() # allow GET/PUT/POST/DELETE/PATCH
def prepend_urls(self):
return [
url(r"^track/(?P<resource_name>%s)/$" % self._meta.resource_name, self.wrap_view('dispatch_list'), name='api_dispatch_list'),
url(r"^track/(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/$" % self._meta.resource_name, self.wrap_view('dispatch_detail'), name='api_dispatch_detail'),
]
在我的ExpenseResource
中处理 client_slug 的最佳方式是什么?我想通过提供的 client_slug 来过滤我的费用,我应该怎么做呢?谢谢!
答案 0 :(得分:3)
实际上非常简单。您可以覆盖base_urls()
或使用override_urls()
或prepend_urls()
提供接受client_slug
的自定义网址。
对于每个资源,Tastypie执行以下操作:
def base_urls(self):
"""
The standard URLs this ``Resource`` should respond to.
"""
# Due to the way Django parses URLs, ``get_multiple`` won't work without
# a trailing slash.
return [
url(r"^(?P<resource_name>%s)%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('dispatch_list'), name="api_dispatch_list"),
url(r"^(?P<resource_name>%s)/schema%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('get_schema'), name="api_get_schema"),
url(r"^(?P<resource_name>%s)/set/(?P<pk_list>\w[\w/;-]*)/$" % self._meta.resource_name, self.wrap_view('get_multiple'), name="api_get_multiple"),
url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('dispatch_detail'), name="api_dispatch_detail"),
]
您需要的是以下内容:
return [
url(r"^(?P<client_slug>\w+)/(?P<resource_name>%s)%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('dispatch_list'), name="api_dispatch_list"),
url(r"^(?P<client_slug>\w+)/(?P<resource_name>%s)/schema%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('get_schema'), name="api_get_schema"),
url(r"^(?P<client_slug>\w+)/(?P<resource_name>%s)/set/(?P<pk_list>\w[\w/;-]*)/$" % self._meta.resource_name, self.wrap_view('get_multiple'), name="api_get_multiple"),
url(r"^(?P<client_slug>\w+)/(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('dispatch_detail'), name="api_dispatch_detail"),
]
只需使用上述方法之一来提供这些方法,然后我相信client_slug
将在kwargs[ 'client_slug' ]
中在所有接受**kwargs
的Tastypie方法中可用。
我没有测试过,但是给出了:
objects = self.obj_get_list(request=request, **self.remove_api_resource_names(kwargs))
在get_list()
中,它甚至可以为您提供开箱即用的费用。