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

Popular posts from this blog

symfony - TEST environment only: The database schema is not in sync with the current mapping file -

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -