Can to_representation() in Django Rest Framework access the normal fields

Question:

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.

Here’ the documentation link:

http://www.django-rest-framework.org/api-guide/serializers/#overriding-serialization-and-deserialization-behavior

Here is my current code:

from django.forms.models import model_to_dict

class PersonListSerializer(serializers.ModelSerializer):

    class Meta:
        model = Person
        fields = ('foo', 'bar',)

    def to_representation(self, instance):
        return model_to_dict(instance)

When I do this code, it returns all fields in the model instead of the fields that I have specified above in class Meta: fields.

Is it possible to reference the class Meta: fields within the to_representation method?

Asked By: Aaron Lelevier

||

Answers:

DRF’s ModelSerializer already has all the logic to handle that. In your case you shouldn’t even need to customize to_representation. If you need to customize it, I would recommend to first call super and then customize the output:

class PersonListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Person
        fields = ('foo', 'bar',)

    def to_representation(self, instance):
        data = super(PersonListSerializer, self).to_representation(instance)
        data.update(...)
        return data

P.S. if you are interested to know how it works, the magic actually does not happen in ModelSerializer.to_representation. As a matter of fact, it does not even implement that method. Its implemented on regular Serializer. All the magic with Django models actually happens in get_fields which calls get_field_names which then considers the Meta.fields parameters…

Answered By: miki725
def to_representation(self, instance):
    data = super(ResultLogSerializer, self).to_representation(instance)
    data['username'] = instance.job_result.user.username
    data['status'] = instance.job_result.status
    data['created'] = instance.job_result.created
    data['completed'] = instance.job_result.completed
    return data
Answered By: apishark