How to hydrate a resource_uri in django-tastypie?

2019-05-07 20:32发布

问题:

I just have a Resource uri, like '/api/v1/myobjectresource/23/', and I need to hydrate it. It means, I want to instantiate MyObject(pk=23) from its resource_uri. How should I do this?

回答1:

Extracted from https://gist.github.com/794424

def get_resource_uri(self, bundle_or_obj):

kwargs = {
    'resource_name': self._meta.resource_name,
}
if isinstance(bundle_or_obj, Bundle):
    kwargs['pk'] = bundle_or_obj.obj.id # pk is referenced in ModelResource
else:
    kwargs['pk'] = bundle_or_obj.id
if self._meta.api_name is not None:
    kwargs['api_name'] = self._meta.api_name
return self._build_reverse_url('api_dispatch_detail', kwargs = kwargs)