Using tastypie resource in view

最后都变了- 提交于 2019-12-03 16:08:33

So here I found the solution, the problem was with url resolving ... I needed to add

def get_resource_uri(self, bundle_or_obj):
   return '/api/v1/%s/%s/' % (self._meta.resource_name,bundle_or_obj.obj.id)

to the related object (session here) in order for it to work (don't ask why!)

So here is my working solution for renderDetail and renderList :

def renderDetail(self,pkval):
    request = HttpRequest()
    request.GET = {'format': 'json'}
    resp =  self.get_detail(request, pk=pkval)
    return resp.content


def renderList(self,options={}):
    request = HttpRequest()
    request.GET = {'format': 'json'}
    if len(options) > 0:
        request.GET.update(options)

    resp = self.get_list(request)
    return resp.content

And here is an example usage :

cmr = ChatMessageResource()

dataOne= cmr.renderDetail("723")

dataAll = cmr.renderList({'limit':'0','chat_session':cur_sess.pk})

https://github.com/toastdriven/django-tastypie/issues/962

I've found that obj_get method needs a bundled request object. See the link.

def user_detail(request, username):
    ur = UserResource()
    # Add this request bundle to the obj_get() method as shown.
    req_bundle = ur.build_bundle(request=request)
    user = ur.obj_get(req_bundle, username=username)
    ....

Your problem seems to be here:

data =  self.obj_get(None,pk=pkval)

The parameters to obj_get should be kwargs that can be passed directly to a standard get. None should not be in there.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!