Reputation: 2324
I have two resources: UserResource and ChannelResource, as follows:
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'
I can get user listings and info about a single user (including the channels he owns):
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
}
but when I try to get a channel listing for a user, I get an error:
http://localhost/api/users/1/channels/?format=json&limit=0
error_message: "Invalid resource lookup data provided (mismatched type)."
I can see from the above json that the resource is at api/channels/, but I want it to be at api/users/1/channels. How can I accomplish this?
Thanks!
Upvotes: 0
Views: 229
Reputation: 2324
Finally figured it out. The solution is.... ugh. Anyhow, here it is:
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)
Upvotes: 1