Django Rest Framework ListField and DictField

I have a struggle with understanding ListField and DictField . I want to use it as a field in a serializer. I have a ListField that will probably contain a lot of DictField . I tried to write a serializer as shown below:

 class StopOncomingSerialier(serializers.Serializer): idn = serializers.IntegerField(read_only=True) buses = serializers.ListField( child=serializers.DictField( idn=serializers.IntegerField(read_only=True), stops_left=serializers.IntegerField(read_only=True) ), read_only=True ) 

I know this doesn't make sense, as the documentation says that DictField and ListField take child as an argument. So the code above naturally raised an error:

TypeError: __init __ () received an unexpected keyword argument 'stops_left'

Desired output

 { "idn": 1, "buses": [ {"idn": 11, "stops_left": 4}, {"idn": 12, "stops_left": 15} ] } 

How to achieve this? buses is a list and can contain as many elements as possible.


Environment

  • python 3.5.1
  • django 1.9.6
  • django-rest-framework 3.3.3
+6
source share
1 answer

I think you should use nested serializers instead.

Create a BusSerializer with idn and stops_left . Then include this serializer in the StopOncomingSerializer field as buses with the argument many=True to process multiple buses data.

 class BusSerializer(serializers.Serializer): idn = serializers.IntegerField(read_only=True) stops_left = serializers.IntegerField(read_only=True) class StopOncomingSerialier(serializers.Serializer): idn = serializers.IntegerField(read_only=True) buses = BusSerializer(many=True) 
+6
source

All Articles