Django Rest Framework object not repeating?

I serialized one of my models in which there is a foreign key. I get a 'Parent' object is not iterable

models.py

 class Parent(models.Model): # Parent data class Child(models.Model): parent = ForeignKey(Parent) 

serializer.py

 class ChildSerializers(serializers.ModelSerializer): parent = serializers.RelatedField(many=True) class Meta: model = ReportField fields = ( 'id', 'parent' ) 

api.py

 class ChildList(APIView): def get(self, request, format=None): child = Child.objects.all() serialized_child = ChildSerializers(child, many=True) return Response(serialized_child.data) 

I assume I need to pass the parent list to a list of children, but not sure if this is the best way to do this

attempt api.py

 class ChildList(APIView): def get(self, request, format=None): child = Child.objects.all() parent = Parent.objects.all() serialized_child = ChildSerializers(child, many=True) serialized_parent = ChildSerializers(parent, many=True) return Response(serialized_child.data, serialized_parent.data) 
+8
source share
2 answers

Why use many = True. A parent is just one field, no explicit serializer field is needed. Just get rid of these many = True

- submitted by mariodev in the comment.

+20
source
 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
source

Source: https://habr.com/ru/post/977616/


All Articles