django - Rest Framework: HyperlinkedRelatedField, return multiple attributes? -
django rest framework's hyperlinkedrelatedfield used serialize related fields this:
'tracks': [ 'http://www.example.com/api/tracks/45/', 'http://www.example.com/api/tracks/46/', 'http://www.example.com/api/tracks/47/' ]
i'm looking way return multiple attributes, like:
'tracks': [ {'id': 45, 'href': 'http://www.example.com/api/tracks/45/'}, {'id': 46, 'href': 'http://www.example.com/api/tracks/46/'}, {'id': 47, 'href': 'http://www.example.com/api/tracks/47/'} ]
is there way achieve using drf's standard serializers?
you use nested serializer that. serializers in drf usable fields:
class trackserializer(modelserializer): class meta: model = track fields = ('id', 'href') class yourmodelserializer(modelserializer): tracks = trackserializer(many=true)
you have examples in official documentation, pretty close way.
if want read-write access on tracks
field, have override create()
, update()
on yourmodelserializer
. because correct behavior depends on specific application: should update fields of track? should replace associated tracks? if so, should delete associated? if tracks not exist, should create them or return error?
the documentation this thorough.
Comments
Post a Comment