TastyPie资源

时间:2013-06-14 16:00:05

标签: django django-models tastypie

我有两个资源:UserResource和ChannelResource,如下所示:

class ChannelResource(ModelResource):

    class Meta:
        queryset = Channel.objects.all()
        resource_name = 'channels'


class UserResource(ModelResource):
    channels = fields.ToManyField(ChannelResource, 'channels', full=True)
    stories = fields.ToManyField('core.api.StoryResource', 'stories', full=True)

    class Meta:
        queryset = User.objects.all()
        resource_name = 'users'

我可以获得有关单个用户的用户列表和信息(包括他拥有的频道):

http://localhost/api/users/1/?format=json&limit=0
{
  channels: [
  {
    id: 1,
    identifier: "default",
    name: "default",
    resource_uri: "/api/v1/channels/1/"
  }],
  id: 1,
  name: threejeez
}

但是当我尝试为用户获取频道列表时,出现错误:

http://localhost/api/users/1/channels/?format=json&limit=0
error_message: "Invalid resource lookup data provided (mismatched type)."

我可以从上面的json看到资源是在api / channels /,但我希望它在api / users / 1 / channels。我怎么能做到这一点?

谢谢!

1 个答案:

答案 0 :(得分:1)

终于明白了。解决方案是......呃。无论如何,这里是:

def prepend_urls(self):
    return [
        url(r"^(?P<resource_name>%s)/(?P<pk>\d+)/channels%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('get_channels'), name="api_get_channels"),
    ]

def get_channels(self, request, **kwargs):
    basic_bundle = self.build_bundle(request=request)
    obj = self.cached_obj_get(bundle=basic_bundle, **self.remove_api_resource_names(kwargs))
    channel_resource = UserChannelResource()
    try:
        channel_resource._meta.queryset = obj.channels.all()
    except IndexError:
        channel_resource._meta.queryset = Channel.objects.none()

    return channel_resource.get_list(request)