Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从tastypie uri获取模型对象?_Python_Django_Tastypie - Fatal编程技术网

Python 从tastypie uri获取模型对象?

Python 从tastypie uri获取模型对象?,python,django,tastypie,Python,Django,Tastypie,如何从tastypiemodelResource的uri中获取其模型对象 例如: 如果在python中uri是作为字符串提供的,那么如何获取该字符串的模型对象?您正在寻找该字符串吗?这实际上取决于您何时需要对象 在脱水循环中,您可以通过捆绑访问它,例如 class MyResource(Resource): # fields etc. def dehydrate(self, bundle): # Include the request IP in the bun

如何从tastypiemodelResource的uri中获取其模型对象

例如:

如果在python中uri是作为字符串提供的,那么如何获取该字符串的模型对象?

您正在寻找该字符串吗?这实际上取决于您何时需要对象

在脱水循环中,您可以通过捆绑访问它,例如

class MyResource(Resource):
    # fields etc.

    def dehydrate(self, bundle):
        # Include the request IP in the bundle if the object has an attribute value
        if bundle.obj.user:
            bundle.data['request_ip'] = bundle.request.META.get('REMOTE_ADDR')
        return bundle
如果您想通过api url手动检索对象,给定一个模式,您可以通过默认orm方案简单地遍历slug或主键(或任何它是什么?

Tastypie的资源类(guy ModelResource正在子类化)提供了一个方法。请注意,他通过
调用应用授权限制(请求、对象列表)
因此,如果您没有收到所需的结果,请确保以通过授权的方式编辑您的请求

不好的替代方法是使用正则表达式从url提取id,然后使用它过滤所有对象的列表。这是我的肮脏的黑客行为,直到我通过uri获得了工作,我不建议使用它


您可以使用
get\u via\u uri
,但正如@Zakum所提到的,这将应用授权,这可能是您不想要的。因此,深入研究该方法的源代码,我们可以像这样解析URI:

from django.core.urlresolvers import resolve, get_script_prefix

def get_pk_from_uri(uri):
    prefix = get_script_prefix()
    chomped_uri = uri

    if prefix and chomped_uri.startswith(prefix):
        chomped_uri = chomped_uri[len(prefix)-1:]

    try:
        view, args, kwargs = resolve(chomped_uri)
    except Resolver404:
        raise NotFound("The URL provided '%s' was not a link to a valid resource." % uri)

    return kwargs['pk']
如果Django应用程序位于Web服务器的根目录(即
get_script_prefix()='/'
),则可以将其简化为:

view, args, kwargs = resolve(uri)
pk = kwargs['pk']
view, args, kwargs = resolve(uri)
pk = kwargs['pk']