ereOn ereOn - 5 months ago 30
JSON Question

How can one customize Django Rest Framework serializers output?

I have a Django model that is like this:

class WindowsMacAddress(models.Model):
address = models.TextField(unique=True)
mapping = models.ForeignKey('imaging.WindowsMapping', related_name='macAddresses')


And two serializers, defined as:

class WindowsFlatMacAddressSerializer(serializers.Serializer):
address = serializers.Field()

class WindowsCompleteMappingSerializer(serializers.Serializer):
id = serializers.Field()
macAddresses = WindowsFlatMacAddressSerializer(many=True)
clientId = serializers.Field()


When accessing the serializer over a view, I get the following output:

[
{
"id": 1,
"macAddresses": [
{
"address": "aa:aa:aa:aa:aa:aa"
},
{
"address": "bb:bb:bb:bb:bb:bb"
}
],
"clientId": null
}
]


Almost good, except that I'd prefer to have:

[
{
"id": 1,
"macAddresses": [
"aa:aa:aa:aa:aa:aa",
"bb:bb:bb:bb:bb:bb"
],
"clientId": null
}
]


How can I achieve that ?

Answer

Create a custom serializer field and implement to_native so that it returns the list you want.

If you use the source="*" technique then something like this might work:

class CustomField(Field):
    def to_native(self, obj):
        return obj.macAddresses.all()

I hope that helps.

Comments