Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 216
ereOn Avatar asked Aug 02 '13 08:08

ereOn


People also ask

What is Serializers in Django REST framework?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

How do you pass extra context data to Serializers in Django REST framework?

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.

How do I change the foreign key value in Django REST framework?

As stated in the documentation, you will need to write your own create() and update() methods in your serializer to support writable nested data. You will also need to explicitly add the status field instead of using the depth argument otherwise I believe it won't be automatically added to validated_data .

What is To_representation in Django?

The docs on using to_representation is somewhat short. This method is used by Django Rest Framework 3.0+ to change the representation of your data in an API.


1 Answers

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.

Update for djangorestframework>=3.9.1

According to documentation, now you need override either one or both of the to_representation() and to_internal_value() methods. Example

class CustomField(Field):
    def to_representation(self, value)
        return {'id': value.id, 'name': value.name}
like image 115
Carlton Gibson Avatar answered Sep 20 '22 17:09

Carlton Gibson