[Django]-Django Rest Framework object is not iterable?

50👍

Why using many=True. Parent is just a single field, no need to use explicit serializer field. Just get rid of these many=True

-answered by mariodev in comment.

0👍

You can do something like this using python collections as an intermediate

#serializers.py
class TimelineSerializer(serializers.Serializer):
    childs= childSerializer(many=True)
    parents = parentSerializer(many=True)

#apiviews.py
from collections import namedtuple
Timeline = namedtuple('Timeline', ('childs', 'parents'))

def list(self, request):
        timeline = Timeline(
            childs=Child.objects.all(),
            parents=Parent.objects.all(),
        )
        serializer = TimelineSerializer(timeline)
        return Response(serializer.data)

0👍

If your using a ModalSerializer then you have two foreign keys in a modal, then use "to_representation" function like this

def to_representation(self, instance):
        rep = super().to_representation(instance)
        rep['pcatalog_name'] = CatalogSerializer(instance.pcatalog_name).data
        rep['pcategory_name'] = CategorySerializer(instance.pcategory_name).data
        return rep

0👍

Replace ForeignKey by ManyToManyField to clarify the serializer field with many = True

enter image description here

Leave a comment