Overriding URL field on HyperlinkedModelSerializer to support models with composite keys

631 views
Skip to first unread message

David Jones

unread,
Jun 13, 2013, 6:37:00 AM6/13/13
to django-res...@googlegroups.com
Hi there

I have a model with a composite key i.e. it takes two fields to identify a specific instance of the model.

e.g. instead of using an URL like this to identify an employee:
api/1.3/employee/5/

I use an URL like this:
api/1.3/company/23/employee/5/

I use a HyperlinkedModelSerializer to serialise this model.  I couldn't find a way of configuring a HyperlinkedIdentityField to handle the composite key (you can only specify a single lookup_field) so I override the url with a SerializerMethodField instead, like this:

class EmployeeSerializer(serializers.HyperlinkedModelSerializer):
    url = serializers.SerializerMethodField('get_employee_detail_url')

    def get_employee_detail_url(self, obj):
        # generate the URL for the composite key
        ...
        return composite_key_url

This worked fine in version 2.3.4 but fails in 2.3.5.  HyperlinkedModelSerializer.__init__ has been modified and now it overwrites any custom url field with a HyperlinkedIdentityField.  

So...

Is there an alternative way of overriding the URL field?  Should I think about subclassing HyperlinkedModelSerializer?  Or would it be acceptable to modify the initializer to check if self.fields['url'] has already been set before setting it to be the HyperlinkedIdentityField?

Thanks!



David Jones

unread,
Jun 16, 2013, 3:04:15 PM6/16/13
to django-res...@googlegroups.com
This has now been raised as an issue here: https://github.com/tomchristie/django-rest-framework/issues/936

Tom Christie

unread,
Jun 17, 2013, 12:49:35 PM6/17/13
to django-res...@googlegroups.com
This issue should now be fixed in master...


Cheers,

  Tom


On Thursday, 13 June 2013 11:37:00 UTC+1, David Jones wrote:
Reply all
Reply to author
Forward
0 new messages