Search code examples
pythondjangoapitastypie

Django-tastypie multiple urls in prepend_urls


I'm trying to add two different methods of accessing the same ResourceModel through the prepend_urls() functionality in Django-tastypie, but the second url never works.

Here is the code I have:

class UserResource(ModelResource):
    class Meta:
        ...
        my_id_uri_name = 'my_id'
        name_uri_name = 'name'

    def prepend_urls(self):
        return [
            url(
                r"^(?P<resource_name>%s)/(?P<my_id>[\w\d_.-]+)/$"
                % self._meta.resource_name, self.wrap_view('dispatch_detail'),
                name="api_dispatch_detail_my_id"),
            url(
                r"^(?P<resource_name>%s)/(?P<name>[\w\d_.-]+)/$"
                % self._meta.resource_name, self.wrap_view('dispatch_detail'),
                name="api_dispatch_detail_name"),
        ]

I cannot find any helpful resources about adding an additional URL here. Am I missing something trivial?


Solution

  • I've solved this, thanks to Zeograd's suggestion about regexp.

    I changed the first {ID} expression to match on an integer and the second on a string, like so:

    def prepend_urls(self):
            return [
                url(
                    r"^(?P<resource_name>%s)/(?P<my_id>\d+)/$"
                    % self._meta.resource_name, self.wrap_view('dispatch_detail'),
                    name="api_dispatch_detail_id"),
                url(
                    r"^(?P<resource_name>%s)/(?P<name>[\w\d_.-]+)/$"
                    % self._meta.resource_name, self.wrap_view('dispatch_detail'),
                    name="api_dispatch_detail_name"),
            ]