1

我正在尝试构建如下 API:

api/v1/<client_slug>/track/expenses

/clients但是,至少在此时,我并没有真正需要返回的任何数据,所以我希望避免必须创建一个 ClientResource 来遵循 REST 标准。下面是我的 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'),
        ]

将client_slug包含在我的 中的最佳处理方法是什么ExpenseResource?我想通过提供的client_slug过滤我的费用,我应该怎么做?谢谢!

4

1 回答 1

3

其实很简单。您可以覆盖base_urls()或使用override_urls()prepend_urls()提供接受的自定义 URL 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' ]在所有接受的 Tastypie 方法中可用**kwargs

我没有测试它,但给出:

 objects = self.obj_get_list(request=request, **self.remove_api_resource_names(kwargs))

get_list()甚至可以为您过滤开箱即用的客户费用。

于 2012-09-05T02:37:23.397 回答