Monday, 15 July 2013

Django REST Meta data for M2M missing -



Django REST Meta data for M2M missing -

on json output don't seem key value pairs on m2m field attribute_answers. see code below. how add together in attribute_answers fields?

json

{ "id": 20, "name": "jake", "active": true, "type": { "id": 1, "name": "human", "active": true, "created": "2013-02-12t13:31:06z", "modified": null }, "user": "jason", "attribute_answers": [ 1, 2 ] }

serializer

class profileserializer(serializers.modelserializer): user = serializers.slugrelatedfield(slug_field='username') attribute_answers = serializers.primarykeyrelatedfield(many=true) class meta: model = profile depth = 2 fields = ('id', 'name', 'active', 'type', 'user', 'attribute_answers') def restore_object(self, attrs, instance=none): """ create or update new snippet instance. """ if instance: # update existing instance instance.name = attrs.get('name', instance.name) instance.active = attrs.get('active', instance.active) instance.type = attrs.get('type', instance.type) instance.attribute_answers = attrs.get('attribute_answers', instance.attribute_answers) homecoming instance # create new instance homecoming profile(**attrs)

if understand question correctly, want nested relationship. in profileserializer, you'll want:

attribute_answers = attributeanswerserializer(many=true)

this display attributes of each associated attribute_answer model , give like:

{ "id": 20, "name": "jake", "active": true, "type": { "id": 1, "name": "human", "active": true, "created": "2013-02-12t13:31:06z", "modified": null }, "user": "jason", "attribute_answers": [ {"id": 1, "foo": "bar"}, {"id": 2, "foo": "bar2"} ] }

django django-rest-framework

No comments:

Post a Comment