使用tastypie,如何在单个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'}]
});
这不起作用。我被告知,“'歌'字段的数据不是URI,不是字典,而且没有'pk'属性”。是否有可能像这样一次性插入一条记录,还是我需要发送单独的播放列表和每首歌曲的请求?
答案 0 :(得分:1)
只是非常非常快速地玩它(而且我是tastypie的新手,所以请注意这一点) - 我认为你可以通过覆盖资源中的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)
答案 1 :(得分:0)
你想做这样的事情:
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/
祝你好运!