Getting an empty list when using filter - Django REST

Viewed 317

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>/shipments', GetItemsByEmail.as_view()),
   ]

My Question:

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?

2 Answers

If you want your query to be case insensitive, you can try the following:

myModel.objects.filter(user_email__iexact=email_items)

In your views.py:

from rest_framework import generics
from .models import *  # noqa
from .serializers import *


class GetItemsByEmail(generics.ListAPIView):
    queryset = MyModel.objects.all()  # noqa
    serializer_class = MyModelSerializer

    def get_queryset(self):
        if self.kwargs.get('user_email_pk'):
            return self.queryset.filter(id=self.kwargs.get('user_email_pk'))
        return self.queryset.all()

In models.py I had to create another model to have the result that you want (get all database by a specific user_email!):

from django.db import models


class MyModel(models.Model):
    user_email = models.CharField(max_length=200, null=False)

    def __str__(self):
        return self.user_email


class ServicesModel(models.Model):
# Just an example to emulate the expected result, do not worry about it!
    name = models.CharField('Name', max_length=200)
    user_email_service = models.ForeignKey(MyModel, related_name='services', on_delete=models.CASCADE) # Just an example to emulate the expected result, do not worry about it!

    def __str__(self):
        return self.name

In serializers.py:

from rest_framework import serializers
from .models import MyModel, ServicesModel


class ServiceModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = ServicesModel
        fields = (
            'name',
        )


class MyModelSerializer(serializers.ModelSerializer):

    services = ServiceModelSerializer(many=True, read_only=True)

    class Meta:
        model = MyModel
        fields = (
            'id',
            'user_email',
            'services',
        )

In urls.py:

from django.urls import path

from core.views import GetItemsByEmail

urlpatterns = [
   path('users/', GetItemsByEmail.as_view(), name='users'),  # Ignore!
   path('users/account=<str:user_email_pk>/shipments/', GetItemsByEmail.as_view(), name='user_email'),
   ]

In the test that I made localy I created two 'user_email' and each one have diferent 'services' so you are able to get all the data by the id, images of the result:

  1. enter image description here
  2. enter image description here

You obviously only need to get attention in 'views.py' and 'serializers.py', I just created all this code to get in the expected result!

Related