Skip to content

Serializers

Oliver Roick edited this page Feb 17, 2016 · 3 revisions

DetailSerializer

core.serializers.DetailSerializer allows you to create compact representations on your model instances, by excluding fields from serialization. This can be useful when serializing a compact list of model instances and only provide detailed information when accessing a single instance.

DetailSerializer automatically creates compact representations whenever you attempt to serialize a list of model instances. To force detailed serialization with lists, add detail=True as a keyword argument when initializing the serializer.

Example use:

To use DetailSerializer, add it to the list of base classes, usually it goes next the Rest Framework's ModelSerializer. To exclude fields from the compact view, add the field name to the detail_only_fields attribute in the serializer's Meta class.

from core.serializers import DetailSerializer
from rest_framework.serializers import ModelSerializer

class OrganizationSerializer(DetailSerializer, ModelSerializer):
    class Meta:
        model = Organization
        fields = ('id', 'slug', 'name', 'description', 'archived', 'urls',
                  'contacts', 'users')
        read_only_fields = ('id',)
        detail_only_fields = ('users',)

Instantiate the serializer normally:

org = some_list_of_organizations;

s = OrganizationSerializer(org)
s.data  # returns organizations without users, if org is a list.

For detailed representations with lists:

org = some_list_of_organizations;

s = OrganizationSerializer(org, detail=True)
s.data  # returns organizations including users
Clone this wiki locally