Writable Nested Serializer with AngularJS

33 views
Skip to first unread message

Ashish Gupta

unread,
Jan 15, 2016, 10:25:16 AM1/15/16
to Django REST framework
I am trying to use Writable Nested Serializer with AngularJS. I have image field in the related model. So its something like this:

class TrackSerializer(serializers.ModelSerializer):
    class Meta:
        model = Track
        fields = ('order', 'title', 'duration', 'thumbnail')  # ImageField here

class AlbumSerializer(serializers.ModelSerializer):
    tracks = TrackSerializer(many=True)

    class Meta:
        model = Album
        fields = ('album_name', 'artist', 'tracks')

    def create(self, validated_data):
        tracks_data = validated_data.pop('tracks')
        album = Album.objects.create(**validated_data)
        for track_data in tracks_data:
            Track.objects.create(album=album, **track_data)
        return album
Now I want to post the data in the docs its mentioned like this -

>>> data = {
    'album_name': 'The Grey Album',
    'artist': 'Danger Mouse',
    'tracks': [
        {'order': 1, 'title': 'Public Service Announcement', 'duration': 245},
        {'order': 2, 'title': 'What More Can I Say', 'duration': 264},
        {'order': 3, 'title': 'Encore', 'duration': 159},
    ],
}
>>> serializer = AlbumSerializer(data=data)
>>> serializer.is_valid()
True
>>> serializer.save()
<Album: Album object>
How to achieve same using AngularJS. I am trying to do the same using FormData in AngularJS. But its returning the nested object as string list instead of list.

How to post data using AngularJS forms with imagefield in Nested model. I am even not able to replicate the above case because the Angular is returning like this in request.data -



{
    'album_name': 'The Grey Album',
    'artist': 'Danger Mouse',
    'tracks': "[
        {'order': 1, 'title': 'Public Service Announcement', 'duration': 245},
        {'order': 2, 'title': 'What More Can I Say', 'duration': 264},
        {'order': 3, 'title': 'Encore', 'duration': 159},
    ]",  # note that list here is unicode instead of list
}

How should this be done ?
Reply all
Reply to author
Forward
0 new messages