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?
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.
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.
The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.
SlugRelatedField may be used to represent the target of the relationship using a field on the target. For example, the following serializer: class AlbumSerializer(serializers. ModelSerializer): tracks = serializers.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With