python - Tastypie 嵌套资源 - cached_obj_get() 正好接受 2 个参数(给定 1 个)

标签 python django python-2.7 tastypie

我正在尝试使用此处的示例:http://django-tastypie.readthedocs.org/en/latest/cookbook.html#nested-resources

出于某种原因我得到:

cached_obj_get() takes exactly 2 arguments (1 given)

尽管我清楚地用 2 个参数调用它(与上述示例完全一样。 这是我的代码:

def prepend_urls(self):
    return [
        url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/feed%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('get_feed'), name="api_get_feed"),
]

def get_feed(self, request, **kwargs):
    try:
        obj = self.cached_obj_get(request=request, **self.remove_api_resource_names(kwargs)) 
    except ObjectDoesNotExist:
        return HttpGone()
    except MultipleObjectsReturned:
        return HttpMultipleChoices("More than one resource is found at this URI.")

    feed_resource = FeedItemResource()
    return feed_resource.get_list(request, p_id=obj.id)

最佳答案

抱歉造成混淆 - 有一个 API change to improve authorization更改了 cached_obj_get 的签名来自:

def cached_obj_get(self, request=None, **kwargs):

def cached_obj_get(self, bundle, **kwargs):

此更改是一致的 - 如果您需要 request 对象,它可以作为 bundle.request 使用 - 但显然需要更新文档。

你可以构建一个包对象:

basic_bundle = self.build_bundle(request=request)

然后将其用作 cached_obj_get 的参数(参见 Resource.get_detail source code 作为示例):

obj = self.cached_obj_get(bundle=basic_bundle, **self.remove_api_resource_names(kwargs))

如果您不熟悉 Python 的对象模型,另一个令人困惑的方面是方法总是至少接收一个参数,因为第一个位置参数总是 object instance or self。并且关键字参数不包括在该计数中,因此“1 给定”意味着该方法仅在期望 selfbundle< 时收到 self 位置参数.

关于python - Tastypie 嵌套资源 - cached_obj_get() 正好接受 2 个参数(给定 1 个),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15157071/

相关文章:

python - 更改后使本地服务器重新加载代码

Python:匹配包含正则表达式代码的两个变量的或

python manage.py migrate登陆错误

python - 您将如何继承并覆盖 Django 模型类以创建 listOfStringsField?

python - 两个日期之间的 SQLALCHEMY 查询

python - 如何在具有偶数个条目的numpy掩码数组中获得单个中位数

django - 图像在 Django 1.8 中不显示

python - 选择汉明距离为零的读数

Python string.join ( list ) 最后一个条目为 "and"

arrays - python : append to numpy array