Getting 'ModelBase' object is not iterable

I'm creating the following view to get the list of fruits and I got this type error message. I don't know what I missed here:

TypeError: 'ModelBase' object is not iterable

views.py

class FruitsList(APIView):

    # To list fruits
    def get(self, request):
        fruits = Fruit.objects.all()
        serializer = FruitSerializer(Fruit, many = True)
        return Response(serializer.data)

serializers.py:

class FruitSerializer(serializers.ModelSerializer):

    class Meta:
        model = Fruit
        fields = [
            'id',
            'name',
            'customers',
        ]

models.py:

class Fruit(models.Model):
    """represents customer fruits"""

    name = models.CharField(max_length = 100)
    customers = models.ManyToManyField(Customer)

    def __str__(self):
        return self.name

Your help is much appreciated!

You're passing the Fruit class into the serializer, whereas the serializer expects to receive a list of objects of that class or a queryset of it. So you need to change your views to:

class FruitsList(APIView):

    # To list fruits
    def get(self, request):
        fruits = Fruit.objects.all()
        # This is where the error is, pass in `fruits` instead, not the class
        serializer = FruitSerializer(fruits, many=True)
        return Response(serializer.data)
Back to Top