I have my API in Django REST Framework:
Here is my models.py:
class myModel(models.Model): user_email = models.CharField(max_length= 200, null= False)
Here is my views.py:
class GetItemsByEmail(generics.ListAPIView): def get_queryset(self): email_items = self.request.query_params.get("user_email") if(email_items is not None): itemsReturned = myModel.objects.all().filter(user_email = email_items) return Response(data= itemsReturned)
Here is my urls.py:
url_patterns = [ path('users/account=<str:id>/items', GetItemsByEmail.as_view()), ]
I am getting an empty list, getting nothing from making an API call to the above endpoint. I want to get all the items in the database associated with a particular email, but the filter is not working ? What is the reason behind that ?
You defined the parameter in the URL, so this is an URL parameter.
request.query_params is however not determined by the path, but by the query string [wiki].
You obtain URL parameters through
class GetItemsByEmail(generics.ListAPIView): def get_queryset(self): # use self.kwargs ↓ email_items = self.kwargs.get('user_email') if email_items is not None: return myModel.objects.filter(user_email=email_items) else: # return some queryset pass
urls.py should be updated to work with
url_patterns = [ path('users/account=<str:user_email>/items', GetItemsByEmail.as_view()), ]
While it is not impossible, it is not very common to have an equal sign in the URL, nor to include an email address, these are typically done through the query string or in case of non-GET requests in the payload of the request or the headers.