在get_resource_uri中构建反向URL

sch*_*eck 5 django tastypie

如果有人阅读Tastypie-Mailinglist:我没有在那里得到答案,很抱歉在这里交叉.

在Tastypie中,我更改了Resource的URL模式,因为我使用的是另一个键而不是PK.当我访问资源时,这工作正常.现在我想将此资源嵌套到父资源中,但嵌套的资源包含带有PK的URI,而不是我的自定义密钥.我学到的是,在我的情况下,我必须改变孩子的get_resource_uri.

我孩子的资源(NamespacedResource)中的方法如下所示:

def get_resource_uri(self, bundle_or_obj):

    obj = bundle_or_obj.obj if isinstance(bundle_or_obj, Bundle) else bundle_or_obj

    kwargs={
        'resource_name': self._meta.resource_name,
        'custom_id': obj.custom_id
        }

    return self._build_reverse_url('api_dispatch_detail', kwargs=kwargs)
Run Code Online (Sandbox Code Playgroud)

孩子的网址覆盖方法是这样的:

def override_urls(self):
    return [
        url(r"^(?P<resource_name>%s)/(?P<custom_id>[-_\w\d]+)%s$" % (
                self._meta.resource_name,
                trailing_slash()
            ),
            self.wrap_view('dispatch_detail'),
            name="api_dispatch_detail"
        ),
    ]
Run Code Online (Sandbox Code Playgroud)

但是应用程序无法反转URL.我收到此错误:

Reverse for 'api_dispatch_detail' with arguments '()' and keyword arguments '{'custom_id': u'3_ee5-4423', 'resource_name': 'myresource'} not found.
Run Code Online (Sandbox Code Playgroud)

如何正确反转URL?

提前致谢.

Ani*_*cha 2

tastypie 的内部 url 始终需要resource_name和api_namekwargs。

你的 kwargs 应该包含:

kwargs = {
    'api_name': 'v1',  # Or whatever you have set for your api
    'resource_name': self._meta.resource_name,
    'custom_id': obj.custom_id
}
Run Code Online (Sandbox Code Playgroud)