REST API endpoint call of a single id gives other id results with similar begining alphabtes when called by name

Viewed 38

I am learning REST API Django and would appreciate your help in understaing the below case.

in myproject/abcapp/forms.py

from django import forms
from .models import *

class ProfileForm(forms.ModelForm):
    class Meta:
        model=Profile
        fields = "__all__"
       
  
class Zoo_data_2020Form(forms.ModelForm):
    class Meta:
        model=Zoo_data_2020
        fields = "__all__"

in myproject/abcapp/models.py

from django.conf import settings
from django.db import models


class ProfileQuerySet(models.QuerySet):
    pass

class ProfileManager(models.Manager):
    def get_queryset(self):
        return ProfileQuerySet(self.model,using=self._db)


class Profile(models.Model):
    name=models.CharField(settings.AUTH_USER_MODEL,max_length=200) 
    subtype=models.CharField(max_length=500)
    type=models.CharField(max_length=500)
    gender=models.CharField(max_length=500)
  
    objects = ProfileManager()

    class Meta:
        verbose_name = 'Profile'
        verbose_name_plural = 'Profiles'

        managed = False
        db_table ='profiles'

    def __str__(self):
        return '{}'.format(self.name)
          
      
class Zoo_data_2020QuerySet(models.QuerySet):
    pass
  
class Zoo_data_2020Manager(models.Manager):
    def get_queryset(self):
        return Zoo_data_2020QuerySet(self.model,using=self._db)

class Zoo_data_2020(models.Model):
    name=models.CharField(max_length=200)
    size=models.DecimalField(decimal_places=3,max_digits=100000000)
    weight=models.DecimalField(decimal_places=3,max_digits=100000000)
    age=models.DecimalField(decimal_places=3,max_digits=100000000)
    
    objects = Zoo_data_2020Manager()

    class Meta:
        verbose_name = 'zoo_data_2020'
        verbose_name_plural = 'zoo_data_2020s'

        managed = False
        db_table ='zoo_data_2020'

    def __str__(self):
        return '{}'.format(self.name)

in myproject/abcapp/api/views.py:

from rest_framework import generics, mixins, permissions
from rest_framework.views import APIView
from rest_framework.response import Response
import json
from abcapp.models import *
from .serializers import *


def is_json(json_data):
    try:
        real_json = json.loads(json_data)
        is_valid = True
    except ValueError:
        is_valid = False
    return is_valid


class ProfileDetailAPIView(generics.RetrieveAPIView):
    
    permission_classes = []
    authentication_classes = []
    queryset= Profile.objects.all()
    serializer_class = ProfileSerializer
    lookup_field = 'id'


class ProfileAPIView(generics.ListAPIView):
    permission_classes = []
    authentication_classes= []
    serializer_class = ProfileSerializer

    passed_id = None
    search_fields = ('id','name','animal')
    queryset = Profile.objects.all()


    def get_queryset(self):
        qs = Profile.objects.all()
        query = self.request.GET.get('q')
        if query is not None:
            qs=qs.filter(name__icontains=query)
        return qs


  
class Zoo_data_2020DetailAPIView(generics.RetrieveAPIView):
    
    permission_classes = []
    authentication_classes = []
    queryset= Zoo_data_2020.objects.all()
    serializer_class = Zoo_data_2020Serializer
    lookup_field = ('id','name')
 

class Zoo_data_2020APIView(generics.ListAPIView):
    permission_classes =[]
    authentication_classes= []
    serializer_class = Zoo_data_2020Serializer

    passed_id = None
    search_fields = ('id','name')
    queryset = Zoo_data_2020.objects.all()


    def get_queryset(self):
        qs = Zoo_data_2020.objects.all()
        query = self.request.GET.get('q')
        if query is not None:
            qs=qs.filter(name__icontains=query)
        return qs

in myproject/abcapp/api/serializers.py:

from rest_framework import serializers 
from abcapp.models import *
 
class ProfileSerializer(serializers.ModelSerializer):
     class Meta:
        model=Profile
        fields = "__all__"
        
        read_only_fields = ['name']

class Zoo_data_2020Serializer(serializers.ModelSerializer):
     class Meta:
        model = Zoo_data_2020
        fields = "__all__"
        
        read_only_fields = ['name']

So when i call http://127.0.0.1:8000/api/zoodata2020/?search=AKE it gives me information about AKE but also information about name AKELA which is also in zoodata2020 table. What to do so that i only get information about AKE ?

[
    {
        "id": 7,
        "name": "AKE",
        "subtype": "beaver",
        "type": "arctic",
        "gender": "female",
   
       
    },
    {
        "id": 19,
        "name": "AKELA",
        "subtype": "wolf",
        "type": "arctic",
        "gender": "male",
   
       
    }
]

So i need only id 7 but not 19 and i call by name. The same issue when i call by http://127.0.0.1:8000/api/zoodata2020/?search=24 it lists me id 24,224,2424. Even if i call .../?search=24,24 it would give id 2424. Though it should return:

HTTP 404 Not Found
Allow: GET, HEAD, OPTIONS
Content-Type: application/json

{
   "detail": "Not found."
}

But it does not. Where i need to look and what i need to fix and how.

So tried to do changes in qs=qs.filter(name__icontains=query) to qs=qs.filter(name__exact=query) but ut still does not work.

Would appreciate if you could help to understand it.

1 Answers

qs=qs.filter(name__icontains=query) line performs a pattern matching filtering. If you need exact filtering, then use __exact postfix instead of __contains:

qs=qs.filter(name__exact=query)
Related