Adding Many Serializer to A Nested Serializer Fiel

2019-07-13 22:16发布

问题:

serializers.py

class BusOncomingSerializer(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 = BusOncomingSerializer(many=True)

I have my serializer instances which are valid in a list as below:

buses_serializers = [bus1, bus2, bus3]
# busX means instance of BusOncomingSerializer and they are valid.

I am trying to add these BusOncomingSerializer instances to a single StopOncomingSerializer instance by:

serializer = serializers.StopOncomingSerializers(data={"idn": 1, "buses": buses_serializers})

And I run is_valid(). However, it raises:

TypeError: BusOncomingSerializer(data={'idn': 285, 'stops_left': 7}): idn = IntegerField(read_only=True) stops_left = IntegerField(read_only=True) is not JSON serializable

Should I not add my serializer instances with a list, is there another way?


Environment

  • python 3.5.1
  • django 1.9.5
  • django-rest-framework 3.3.3

回答1:

You are passing the data incorrectly to StopOncomingSerializer. Instead of passing bus instances, you should pass the values as list of dictionaries.

Sample Data format:

{
    'idn': 7, 
    'buses': [
        {'idn':3, 'stops_left': 3}, 
        {'idn': 4, 'stops_left':6}
    ]
}

On Python Shell:

In [5]: data = {'idn': 7, 'buses': [{'idn':3, 'stops_left': 3}, {'idn': 4, 'stops_left':6}]}

In [6]: s1 = StopOncomingSerialier(data=data)

In [7]: s1.is_valid()
Out[7]: True