Can to_representation () in Django Rest Framework access normal fields

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

Here is the link to the documentation:

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 specified above in class Meta: fields .

Is it possible to refer to the class Meta: fields in the to_representation method?

+5
source share
1 answer

The DRF ModelSerializer already has all the logic to handle this. In your case, you don’t even need to configure to_representation . If you need to configure it, I would recommend calling super first and then setting up 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 

PS if you are interested in knowing how this works, magic doesn't actually happen in ModelSerializer.to_representation . In fact, he does not even implement this method. Its implemented on a regular Serializer . All the magic with Django models actually happens in get_fields , which calls get_field_names , which then takes Meta.fields parameters into account ...

+16
source

All Articles