Search code examples
pythondjangoapitastypie

Tastypie access resource by parameter other than PK


I am having a hard time figuring out how to ask this question.

I have a model User. Currently when I want to access a specific user I go to the url: /api/v1/user/8/. Although, all users have unique usernames, so I would like to go to a specific user by using the url: /api/v1/user/joe/.

Maybe something with prepend_urls()?


Solution

  • You need to use detail_uri_name in your ModelResource's Meta class (documentation) - example resources.py:

    from django.contrib.auth.models import User
    from tastypie.resources import ModelResource
    
    
    class UserResource(ModelResource):
        class Meta:
            queryset = User.objects.all()
            allowed_methods = ['get']
            detail_uri_name = 'username'