从tastypeuri获取模型对象?

2024-09-30 16:21:31 发布

您现在位置:Python中文网/ 问答频道 /正文

如何从tastypemodelresource的uri中获取模型对象?在

例如:

如果在python中将uri作为一个字符串给出,那么如何获得该字符串的model对象?在


Tags: 对象字符串模型modeluri中将tastypemodelresource
3条回答

您可以使用get_via_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() == '/'),则可以将其简化为:

^{pr2}$

tastype的资源类(ModelResource的子类)提供了一个方法^{}。请注意,他的呼叫是通过apply_authorization_limits(request, object_list)的,因此如果您没有收到所需的结果,请确保以通过您的授权的方式编辑您的请求。
一个糟糕的替代方法是使用regex从url中提取id,然后使用它过滤所有对象的列表。这是我的肮脏的黑客,直到我让你通过你的乌里工作,我不建议使用这个。;)

id_regex = re.compile("/(\d+)/$")
object_id = id_regex.findall(your_url)[0]
your_object = filter(lambda x: x.id == int(object_id),YourResource().get_object_list(request))[0]

你在找flowchart?这取决于你什么时候想要这个对象。在

在脱水循环中,你可以简单地通过捆绑获得它,例如

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或主键(或其他类型)?在

相关问题 更多 >