Created
September 21, 2012 14:29
-
-
Save BrianHicks/3761789 to your computer and use it in GitHub Desktop.
Override URI field in TastyPie
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
Usage: | |
class MyResource(CustomURIResource): | |
class Meta: | |
queryset = User.objects.all() | |
resource_name = 'user' | |
url_field = 'username' | |
Will make accessible URIs like so: | |
/api/v1/user/<username>/ | |
and produce them from list and detail views. | |
''' | |
class CustomURIResource(ModelResource): | |
'subclass of ModelResource for completely overriding URI field.' | |
def override_urls(self): | |
return [ | |
url( | |
r"^(?P<resource_name>%s)/(?P<%s>[\w\d_.-]+)/$" % (self._meta.resource_name, self._meta.url_field), | |
self.wrap_view('dispatch_detail'), name="api_dispatch_detail" | |
), | |
] | |
def dehydrate_resource_uri(self, bundle): | |
'hydrate resource_uri' | |
return '/api/v1/%s/%s/' % ( | |
self._meta.resource_name, | |
getattr(bundle.obj, self._meta.url_field) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment