Home > database >  How to filter with rest api django?
How to filter with rest api django?

Time:02-06

I have this model:

class Item(models.Model):
        
        category = models.CharField(max_length=255)
        subcategory = models.CharField(max_length=255)
        name = models.CharField(max_length=255)
        amount = models.PositiveIntegerField()
  
        def __str__(self) -> str:
            return self.name

serializer:

class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = ('category', 'subcategory', 'name', 'amount')  

views.py:

@api_view(['GET'])
def view_items(request):
    
    queryset = Item.objects.all() 
    serializer = ItemSerializer(queryset, many=True)
    
    # checking for the parameters from the URL
    if request.query_params:
        items = Item.objects.filter(**request.query_params.dict())
    else:
        items = queryset
  
    # if there is something in items else raise error
    if items:
       
        return Response(serializer.data)
    else:
        return Response(status=status.HTTP_404_NOT_FOUND)

 @api_view(['GET'])
    def ApiOverview(request):
        api_urls = {
            'all_items': '/',
            'Search by Category': '/?category=category_name',
            'Search by Subcategory': '/?subcategory=subcategory_name',
            
        }
    
        return Response(api_urls)

urls.py:

urlpatterns = [
    path('', CategoryViewSet.ApiOverview, name='home'),
    path('all/', views.view_items, name='view_items'),
]

So if I go to: http://127.0.0.1:8000/djangoadmin/all/

[
    {
        "category": "food",
        "subcategory": "vegetaries",
        "name": "potato",
        "amount": 4
    },
    {
        "category": "food",
        "subcategory": "vegetaries",
        "name": "ananas",
        "amount": 5
    },
    {
        "category": "food",
        "subcategory": "fruit",
        "name": "apple",
        "amount": 3
    }
]

So that works.

But now I want to return where subcategory=vegetaries.

So I try like: http://127.0.0.1:8000/djangoadmin/all/?subcategory=vegetaries

But then it returns all items:

[
    {
        "category": "food",
        "subcategory": "vegetaries",
        "name": "potato",
        "amount": 4
    },
    {
        "category": "food",
        "subcategory": "vegetaries",
        "name": "ananas",
        "amount": 5
    },
    {
        "category": "food",
        "subcategory": "fruit",
        "name": "apple",
        "amount": 3
    }
]

Question: how to filter by subcategory?

CodePudding user response:

There is one bug in your code when you get the data from query_params then you not assigned in serializer and you are returning(serializer.data) in response. Here is the updated code

@api_view(['GET'])
def view_items(request):
    # checking for the parameters from the URL
    if request.query_params:
        items = Item.objects.filter(**request.query_params.dict())
        serializer = ItemSerializer(items , many=True)
    else:
        items= Item.objects.all() 
        serializer = ItemSerializer(items , many=True)
  
    # if there is something in items else raise error
    if items:
        return Response(serializer.data)
    else:
        return Response(status=status.HTTP_404_NOT_FOUND)
  • Related