I am currently developping an API using Django.
However, I would like to create a view that return the current User with the following endpoint: /users/current
.
To do so, I created a list view and filtered the queryset to the user that made the request. That works but the result is a list, not a single object. Combined to the pagination, the result looks way too complicated and inconsistant with the other endpoints.
I also tried to create a detail view and filtering the queryset but DRF complains that I provided no pk or slug.
Do you have any idea ?
The best way is to use the power of
viewsets.ModelViewSet
like so:viewsets.ModelViewSet
is a combination ofmixins.CreateModelMixin
+mixins.RetrieveModelMixin
+mixins.UpdateModelMixin
+mixins.DestroyModelMixin
+mixins.ListModelMixin
+viewsets.GenericViewSet
. If you need just list all or get particular user including currently authenticated you need just replace it like thisI used a ModelViewSet like this:
With something like this you're probably best off breaking out of the generic views and writing the view yourself.
You could also do the same thing using a class based view like so...
Of course, there's also no requirement that you use a serializer, you could equally well just pull out the fields you need from the user instance.
Hope that helps.
If you must use the generic view set for some reason, you could do something like this,
retrieve
method is called when the client requests a single instance using an identifier like a primary key/users/10
would trigger the retrieve method normally. Retrieve itself callsget_object
. If you want the view to always return the current used then you could modifyget_object
and forcelist
method to return a single item instead of a list by calling and returningself.retrieve
inside it.Instead of using full power of ModelViewSet you can use mixins. There is RetrieveModelMixin used to retrieve single object just like it is mentioned here - http://www.django-rest-framework.org/api-guide/viewsets/#example_3
If you need also update your model, just add UpdateModelMixin.