Skip to content

Serializers

amplifi edited this page Jun 29, 2017 · 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

SanitizeFieldSerializer

(Preliminary; this is part of PR #1395, which has not been merged yet).

core.serializers.SanitizeFieldSerializer must be added to all serializers that accept user input. It makes sure all fields are sanitized (HTML tags and emojis removed; strings cannot start with +, -, @ or =.

JSONAttrsSerializer

(Preliminary; this is part of PR #1395, which has not been merged yet).

core.serializers.JSONAttrsSerializer must be added to all serializers that create and update models that have a JSONAttributeField field (currently Party, SpatialUnit and TenureRelationship). It validates all entries of the field against the corresponding schema, making sure only fully valid values are added to the database.

If you create new models and add a JSONAttributeField, the JSONAttributeField's name must be attributes for the serializer to work as expected. The validation functionality is implemented into the serializer's validate_attributes method.

Clone this wiki locally