[Answered ]-Rest Framework: HyperlinkedRelatedField, return multiple attributes?

2👍

You would use a nested serializer for that. All serializers in DRF are also usable as fields:

class TrackSerializer(ModelSerializer):
    class Meta:
        model = Track
        fields = ('id', 'href')

class YourModelSerializer(ModelSerializer):
    tracks = TrackSerializer(many=True)

You have examples in the official documentation, pretty close to that by the way.

If you want read-write access on the tracks field, you will have to override create() and update() on YourModelSerializer. This is because the correct behavior depends on your specific application: should it update the fields of the track? should it replace the associated tracks? if so, should it delete those that were associated? what if some tracks do not exist, should it create them or return an error?

The documentation for this is really thorough.

Leave a comment