abstractpaper abstractpaper - 1 year ago 255
Python Question

Django REST Framework - Serializing optional fields

I have an object that has optional fields. I have defined my serializer this way:

class ProductSerializer(serializers.Serializer):
code = serializers.Field(source="Code")
classification = serializers.CharField(source="Classification", required=False)

I thought
would do the job of bypassing the field if it doesn't exist. However, it is mentioned in the documentation that this affects deserialization rather than serialization.

I'm getting the following error:

'Product' object has no attribute 'Classification'

Which is happening when I try to access
of the serialized instance. (Doesn't this mean it's deserialization that's raising this?)

This happens for instances that do not have
. If I omit
from the serializer class it works just fine.

How do I correctly do this? Serialize an object with optional fields, that is.

Answer Source

The serializers are deliberately designed to use a fixed set of fields so you wouldn't easily be able to optionally drop out one of the keys.

You could use a SerializerMethodField to either return the field value or None if the field doesn't exist, or you could not use serializers at all and simply write a view that returns the response directly.

Update for REST framework 3.0 serializer.fields can be modified on an instantiated serializer. When dynamic serializer classes are required I'd probably suggest altering the fields in a custom Serializer.__init__() method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download