Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to filter with rest api django?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@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?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading