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

Assertation Error, You passed a Serializer instance as data, but probably meant to pass serialized `.data` or `.error`. representation

I’m learning drf. I created api using it for minimarket app. After creating some data, i tried to get all of them and i got AssertationError like "You passed a Serializer instance as data, but probably meant to pass serialized .data or .error. representation.
" 🙁 Who knows, what can i do?

views.py

@api_view(['GET'])
def view_items(request):
    
    # checking for the parameters from the URL
    items = Item.objects.all()

    # if there is something in items else raise error
    if items:
        return Response(ItemSerializer(items))
    else:
        return Response(status=status.HTTP_404_NOT_FOUND)

urls.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

from django.urls import path
from . import views

urlpatterns = [
    path('', views.ApiOverview, name='home'),
    path('create/', views.add_items, name='add-items'),
    path('all/', views.view_items, name='view_items'),
]

serializers.py

from pyexpat import model
from django.db.models import fields
from rest_framework import serializers
from .models import Item

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

>Solution :

As the error says, you can not return a serializer in the response:

return Response(ItemSerializer(items))

You can return the data of the serializer, so:

@api_view(['GET'])
def view_items(request):
    # checking for the parameters from the URL
    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