0

我有两个资源: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。我怎样才能做到这一点?

谢谢!

4

1 回答 1

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)
于 2013-06-14T16:56:51.870 回答