0

使用 sweetpie,我将如何在单个 POST 请求中创建一条记录和几条相关记录?

例如,我有这两个资源:

class SongResource(ModelResource):
    playlists = fields.ToManyField('playlists.api.resources.PlaylistResource', 'playlist_set', related_name = "song", full=True)

    class Meta:
        queryset = Song.objects.all();
        resource_name = 'song'
        authorization = Authorization()


class PlaylistResource(ModelResource):
    song = fields.ToOneField(SongResource, 'song', full=True)

    class Meta:
        queryset = Playlist.objects.all()
        resource_name = 'playlist'
        authorization = Authorization()

我想使用带有数据的发布请求一次性创建一个新的播放列表及其歌曲,如下所示:

    var data = JSON.stringify({
        'name': 'My playlist.',
        'songs': [{'title': 'Song 1'}, {'title': 'Song 2'}, {'title': 'Song 3'}]
    });

那是行不通的。有人告诉我,“'song' 字段的数据不是 URI,不是字典,也没有 'pk' 属性”。是否可以像这样一举插入唱片,还是我需要为播放列表和每首歌曲发送单独的请求?

4

2 回答 2

1

只是从非常非常快地玩弄它(而且我是新来的美味派,所以带着一粒盐) - 我认为你可以通过覆盖资源中的 obj_create() 方法来做到这一点。像这样的东西:

class SomeResource(ModelResource):
    class Meta:
        # yadda yadda

    def obj_create(self, bundle, request, **kwargs):
        print "hey we're in object create"
        # do something with bundle.data, this will have your songs in it
        return super(SomeResource, self).obj_create(bundle, request, **kwargs)
于 2012-07-11T22:22:17.267 回答
0

You want to do something like this:

curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"name":"playlist_name", "field2":"value2", "song": ["/api/v1/song/1/"]}' http://localhost:8000/api/v1/playlist/

Good luck!

于 2012-07-11T22:56:43.637 回答