Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework url_pattern of @action

I need to pass instance id after last / of my @action name method, and I seriously have no idea how...

I have a UserViewSet, which url to access list is : /users/, then i have action called favorite_posts, which is detail=False because I'm filtering by current logged user, and the action refer to user posts, I wanna be able to pass the post_id like /users/favorite_posts/post_id/, because in this case it's more friendly to me than /users/1/favorite_posts/ which I could obtain setting detail=True.

Is there any way to do that?

like image 890
slqq Avatar asked Dec 23 '22 02:12

slqq


2 Answers

You can include parameters in your url pattern and have user_id passed to your method like this:

@action(methods=['post'], detail=False, url_path='favorite_posts/(?P<user_id>\d+)', url_name='favorite-posts')
def get_favorite_post(self, request, user_id):
    # Do something
    return Response({...})
like image 119
kaveh Avatar answered Dec 25 '22 15:12

kaveh


You can use it like this:

@action(methods=['get'], detail=False, url_path='req/(?P<post_id>\d+)')

and get post_id in your method like this: kwargs.get('post_id') or just pass post_id directly to your method.

@action(methods=['get'], detail=False, url_path='req/(?P<post_id>\d+)')
def get_post(request, post_id):
     .....
like image 37
Reza Torkaman Ahmadi Avatar answered Dec 25 '22 15:12

Reza Torkaman Ahmadi