[Django]-Custom Hyperlinked URL field for more than one lookup field in a serializer of DRF

6๐Ÿ‘

โœ…

I just needed to do something similar lately. My solution ended up making a custom relations field. To save space, Ill simply (and shamelessly) will point to the source code. The most important part is adding lookup_fields and lookup_url_kwargs class attributes which are used internally to both lookup objects and construct the URIs:

class MultiplePKsHyperlinkedIdentityField(HyperlinkedIdentityField):
    lookup_fields = ['pk']
    def __init__(self, view_name=None, **kwargs):
        self.lookup_fields = kwargs.pop('lookup_fields', self.lookup_fields)
        self.lookup_url_kwargs = kwargs.pop('lookup_url_kwargs', self.lookup_fields)
        ...

That in turn allows the usage like:

class MySerializer(serializers.ModelSerializer):
    url = MultiplePKsHyperlinkedIdentityField(
        view_name='api:my-resource-detail',
        lookup_fields=['form_id', 'pk'],
        lookup_url_kwargs=['form_pk', 'pk']
    )

Here is also how I use it source code.

Hopefully that can get you started.

๐Ÿ‘คmiki725

Leave a comment