You do not need to worry about returning a single object from a set of queries during retrieve . DRF will handle this automatically using the .get_object() defined in GenericAPIView .
You can simply use the code below and DRF will handle the retrieve action for you.
class PortUserView(generics.RetrieveAPIView): lookup_field = 'user' queryset = PortUser.objects.all()
get_object (self)
Returns an instance of the object that should be used for detailed representations. By default, the lookup_field parameter is used to filter the QuerySet database.
Source code for the retrieve action:
def retrieve(self, request, *args, **kwargs): instance = self.get_object()
We see that DRF uses the .get_object() function to get an object from a set of queries. To perform filtering, use lookup_field defined in the view.
Here is the actual get_object() code to make things more clear.
def get_object(self): """ Returns the object the view is displaying. You may want to override this if you need to provide non-standard queryset lookups. Eg if objects are referenced using multiple keyword arguments in the url conf. """ queryset = self.filter_queryset(self.get_queryset())
source share