Created
February 19, 2014 10:26
-
-
Save stephenmcd/9089444 to your computer and use it in GitHub Desktop.
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
from rest_framework import serializers | |
class HyperlinkedIdentityField(serializers.HyperlinkedIdentityField): | |
""" | |
This is a performance wrapper for HyperlinkedIdentityField. | |
We save a ton of time by not calling reverse potentially | |
thousands of times per request. | |
""" | |
def __init__(self, *args, **kwargs): | |
self.view_url = kwargs.pop("view_url", "") | |
super(HyperlinkedIdentityField, self).__init__(*args, **kwargs) | |
def field_to_native(self, obj, field_name): | |
return "http%s://%s%s" % ( | |
"s" if not settings.DEBUG else "", | |
self.context["request"]._request.META["HTTP_HOST"], | |
self.view_url % obj.id, | |
) | |
# Example : | |
# items = HyperlinkedIdentityField(view_url="/api/subscriptions/%s/items/", | |
# view_name="subscription_item_list", pk_url_kwarg="subscription_id") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I know its been a long time @stephenmcd but the improved version of the code won't work as Django is stateless and the urls dict will just reset after each request, sir. You would have to use cache to set the url.