简体   繁体   English

用相关对象扩展stylishpie API

[英]Extending tastypie API with related objects

I'm new to Django, Tastypie and asking questions here. 我是Django,Tastypie的新手,并在这里提问。

I've got a Django application with an API using Tastypie. 我有一个使用Deliciouspie的带有API的Django应用程序。 If I make a GET request to /api/v1/ou/33/ , my API returns the object with the id==33, which is ok. 如果我对/api/v1/ou/33/发出GET请求,我的API会返回id == 33的对象,可以。

{
  "child_ou_uri": "/api/v1/ou/33/child_ou/",
  "displayname": "Mother",
  "id": 33,
  "inherit": true,
  "name": "Mother",
  "resource_uri": "/api/v1/ou/33/"
}

The thing is, I'm trying to extend the API so that it returns related objects via the child_ou_uri URI from the above object. 问题是,我正在尝试扩展API,以便它通过上述对象中的child_ou_uri URI返回相关对象。 The children are the same type of objects as their parents. 孩子是与父母同类型的对象。 The model has an attribute parent_id pointing to the pk of its parent. 该模型具有一个指向其父级pk的属性parent_id

My OuResource looks like this: 我的OuResource看起来像这样:

class OuResource(ModelResource):

    class Meta:
        queryset = OU.objects.all()
        resource_name = 'ou'
        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']
        filtering = {
            'name': ['icontains'],
        }

        authentication = SessionAuthentication()
        authorization = OperatorLocationAuthorization()

    def get_child_ou(self, request, **kwargs):
        self.method_check(request, ['get', ])

        ous = OuResource().get_list(request, parent_id=kwargs['pk'])

        return ous

    def prepend_urls(self):

        return [
            url(r'^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/child_ou%s$' % (self._meta.resource_name, '/'),
            self.wrap_view('get_child_ou'),
            name='api_get_child_ou')
        ]

    def dehydrate(self, bundle):
        kwargs = dict(api_name='v1', resource_name=self._meta.resource_name, pk=bundle.data['id'])

        bundle.data['child_ou_uri'] = reverse('api_get_child_ou', kwargs=kwargs)

        return bundle

When I navigate to /api/v1/ou/33/child_ou/ I'd like to get the list of child objects which have their attribute parent_id set to 33, but instead I get ALL of my objects without any filtering at all, equivalent to me navigating to /api/v1/ou/ . 当我导航到/api/v1/ou/33/child_ou/我想获取其属性parent_id设置为33的子对象列表,但是我得到的所有对象都没有任何过滤,等效对我来说导航到/api/v1/ou/

{
  "meta": {
    "limit": 20,
    "next": "/api/v1/ou/?offset=20&limit=20&format=json",
    "offset": 0,
    "previous": null,
    "total_count": 29
  },
  "objects": [
    {
      "child_ou_uri": "/api/v1/ou/33/child_ou/",
      "displayname": "Mother",
      "id": 33,
      "inherit": true,
      "name": "Mother",
      "resource_uri": "/api/v1/ou/33/"
    },
    {
      "child_ou_uri": "/api/v1/ou/57/child_ou/",
      "displayname": "Mothers 1st child",
      "id": 57,
      "inherit": true,
      "name": "Child 1",
      "resource_uri": "/api/v1/ou/57/"
    },
    {
      "child_ou_uri": "/api/v1/ou/58/child_ou/",
      "displayname": "Mothers 2nd child",
      "id": 58,
      "inherit": true,
      "name": "Child 2",
      "resource_uri": "/api/v1/ou/58/"
    }
  ]
}

What am I missing here? 我在这里想念什么?

[SOLUTION] [解]

Gareth's answer put me on the right track. Gareth的回答使我走上了正确的道路。 I altered my OuResource to look like below. 我将OuResource更改为如下所示。 This allows me to navigate to a url like /api/v1/ou/33/child_ous/ which returns a custom json of the child objects. 这使我可以导航到/api/v1/ou/33/child_ous/这样的网址,该网址返回子对象的自定义json。

class OuResource(ModelResource):
    class Meta:
        queryset = OU.objects.all()
        resource_name = 'ou'
        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']
        filtering = {
            'name': ['icontains'],
        }

        authentication = SessionAuthentication()
        authorization = OperatorLocationAuthorization()

    def prepend_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/(?P<ou_id>\d+)/child_ous%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('child_ous'), name="api_child_ous"),
        ]

    def child_ous(self, request, **kwargs):
        self.method_check(request, allowed=['get'])
        self.is_authenticated(request)
        self.throttle_check(request)

        ous = list(OU.objects.filter(parent_id=kwargs['ou_id']))

        data = []
        for x in ous:
            data.append({
                'id' : x.id,
                'name' : x.name,
                'parent_id' : x.parent_id
            })

        return JsonResponse(data, safe=False)

First, check out the tastypie documentation on creating a search . 首先,查看有关创建搜索的stylishpie文档。

It'd be easier to do this without nesting, eg /api/v1/ou_related/?to=58, but nesting may be desireable for its expressiveness. 不嵌套就更容易做到这一点,例如/ api / v1 / ou_related /?to = 58,但是嵌套可能是可取的,因为它具有表现力。

For nested search with pagification, look at creating another resource, OuSearchResource. 对于具有分页的嵌套搜索,请查看创建另一个资源OuSearchResource。 That resource would override authorized_read_list (and maybe get_list) to pass along the necessary details. 该资源将覆盖authorized_read_list (可能还有get_list)以传递必要的详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM