I am having struggle with understanding ListField
and DictField
. I want to use it as a field on a serializer. I have a ListField
which probably will contain many DictField
. I tried to write a serializer as 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, it does not make sense, since the documentation says DictField
and ListField
take child
as argument. And so, the code above naturally raised error:
TypeError: __init__() got an unexpected keyword argument 'stops_left'
{ "idn": 1, "buses": [ {"idn": 11, "stops_left": 4}, {"idn": 12, "stops_left": 15} ] }
How to achieve this? buses
is a list and might contain as many elements as I want.
DictField is basically a dictionary field that validates the input against a dictionary of objects. It has the following arguments – child – A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.
The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.
In function based views we can pass extra context to serializer with "context" parameter with a dictionary. To access the extra context data inside the serializer we can simply access it with "self. context". From example, to get "exclude_email_list" we just used code 'exclude_email_list = self.
Nope, because not only it's difficult to maintain, but migrating the old data is also a headache. So here what django rest framework comes into play. You can set up apis to be used by your Android application, hence have to maintain a single database against multiple apps.
I think instead of doing that, you should use nested serializers.
Create a BusSerializer
having fields idn
and stops_left
. Then include this serializer in your StopOncomingSerializer
as buses
field with many=True
argument to handle 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With