从Tastypie资源URI获取主键

时间:2014-08-11 20:25:17

标签: django api tastypie

我有一个Django - tastypie资源如下。它有多个具有多对多关系的字段。

我正在尝试获取字段“workflow_initiators”,“workflow_submitters”和“workflow_approvers”,并将用户添加到相应的组,即发起人,提交者和批准者。

我的JSON请求如下:

{

"workflow_approvers": [
"/client/api/v1/user/44/",
"/client/api/v1/user/6/"
],
"workflow_dept": [
"/client/api/v1/departments/1/",
"/client/api/v1/departments/2/"
],
"workflow_initators": [
"/client/api/v1/user/44/",
"/client/api/v1/user/6/"
],
"workflow_name": "Hello Workflow",
"workflow_submitters": [
"/client/api/v1/user/43/",
"/client/api/v1/user/6/"
],

}

我想从 hydrate() obj_create()方法中获取tastypie资源uri的主键。为了得到pk,我使用了一个函数 get_pk_from_uri()。但它会引发以下错误

error : global name 'get_pk_from_uri' is not defined

我的资源如下:


class WorkflowResource(ModelResource):

    workflow_dept = fields.ToManyField(DepartmentsResource, 'workflow_dept', related_name='departments', full=True)
    workflow_initators = fields.ToManyField(UserResource, 'workflow_initators', related_name='user')
    workflow_submitters = fields.ToManyField(UserResource, 'workflow_submitters', related_name='user')
    workflow_approvers = fields.ToManyField(UserResource, 'workflow_approvers', related_name='user')

    def obj_create(self, bundle, **kwargs):
        submitters = bundle.data.get('workflow_submitters', [])
        for submitter in submitters:
            print(get_pk_from_uri(submitter)) # Throws Error

            #Adding User to Group Logic
            # g = Group.objects.get(name='submitters') 
            # g.user_set.add(your_user)

    class Meta:
        queryset = WorkflowIndex.objects.filter(is_active=True)
        resource_name = 'workflows'
        list_allowed_methods = ['get', 'post']
        detail_allowed_methods = ['get', 'post', 'put', 'delete', 'patch']
        serializer = Serializer()
        default_format = 'application/json'
        authentication = Authentication()
        authorization = DjangoAuthorization()
        always_return_data = True


是否有其他方法可以从资源uri获取主键和其他字段?我确实看到了get_via_uri()方法,但不确定如何实现它。

请指导我解决这个问题。

参考文献:

  1. Stackoverflow - Get model object from tastypie uri
  2. Tastypie Documents - get_via_uri()

2 个答案:

答案 0 :(得分:0)

你应该回到这篇文章:Get model object from tastypie uri?

您在this answer中可以看到的get_pk_from_uri(uri)方法不属于Tastypie的源代码,因为您可以查看here

我想这个人是自己写的,你应该做同样的事情,你不会得到error : global name 'get_pk_from_uri' is not defined错误。我没有测试他的方法思想。

答案 1 :(得分:0)

<强>解决方案 大卫是对的。 get_pk_from_uri()不是一个内置的美味馅饼方法,我错了。

P.S:我只是明确答案,以便有人发现它有用。

需要从tastypie的资源uri中提取资源名称或pk。我们将能够从以下部分的** kwargs访问它们。 Kwargs包含以下内容

kwargs
{u'api_name': 'v1', u'pk': '1', u'resource_name': 'workflows'}

将以下代码添加到您的resources.py或utils.py并将其包含在您的API中以获取此方法get_pk_from_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']