Django Rest framework - change the URL hostname in hyperlinkedmodel serializer
<p>I have a webservice built with DRF 1.8.x that is primarily model driven. My intent is to provide absolute URLs in the response for all foreign key fields and this includes the right hostname(gateway hostname). However, since this api sits behind a nginx gateway, the hostname field is modified and sending context['request'] to serializer instance doesn't seem to help.</p>

<p>As of now I'm using decorators for modifying the hostname and handling from version based behaviour for self url field but the forieign key fields are still showing up with api hostname. Here is my code below:</p>

<p>serializers.py</p>

<pre><code>class NodeSerializer(serializers.HyperlinkedModelSerializer):
    url = serializers.SerializerMethodField()

    class Meta:
        model = Node
        fields = ('url', 'name', 'description', 'owner', 'address', 
        'created', 'updated', 'endpoint')
        extra_kwargs= {
             'endpoint': {'view_name': 'loadbalancerendpoint-detail'},
             'owner': {'view_name': 'artifactowner-detail'}
          }

    @set_api_version_ref
    def get_url(self, obj):
        return self.context['request'].META.get('HTTP_REF')
</code></pre>

<p><strong>decorator</strong> - <strong>set_api_version_ref</strong></p>

<pre><code>def set_api_version_ref(f):
    @functools.wraps(f)
    def wrapper(obj, ref):

        base_href = obj.context['request'].META.get('PATH_INFO', None)
        http_host = obj.context['request'].META.get('HTTP_X_HOST', None)
        '''
        Parse the incoming request URL to take API version in to a variable
        '''
        version_parse = re.search('\/myapi\/v(?P&lt;version&gt;(1(\.[0-1])?))\/\w+', base_href)
        api_version = version_parse.group('version')
        logger.debug("API Version detected: {}".format(api_version))
        href_suffix = base_href+str(ref.id)+"/"
        if http_host:
            href =  'https://'+http_host+href_suffix
            base_path = 'https://'+http_host+'/myapi/'+api_version+"/"
        else:
            href = href_suffix
            base_path = '/myapi/v'+api_version+"/"
        logger.debug("href assembled: {}".format(href))
        obj.context['request'].META['API_VERSION'] = api_version
        obj.context['request'].META['HTTP_REF'] = href
        obj.context['request'].META['BASE_PATH'] = base_path
        result = f(obj, ref)
        return result
    return wrapper
</code></pre>

<p>Passing extra_kwargs to related field view names(loadbalancerendpoint-detail, artifactowner-detail etc.,) seem to give me a url back for its pk, but i don't know a way to modify its hostname  with out using a decorator approach like I'm doing it for URL field. Any help here is greatly appreciated, thanks!</p>