Python rest_framework.serializers.ListSerializer() Examples

The following are 30 code examples for showing how to use rest_framework.serializers.ListSerializer(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module rest_framework.serializers , or try the search function .

Example 1
def __init__(self, *args, **kwargs):
            self.child = kwargs.pop('child', copy.deepcopy(self.child))

            self.permission_classes = self.child.permission_classes
            self.check_permission = self.child.check_permission

            self.allow_empty = kwargs.pop('allow_empty', True)

            assert self.child is not None, '`child` is a required argument.'
            assert not inspect.isclass(self.child), '`child` has not been instantiated.'

            # TODO: diagnose/address bad-super-call issue
            # pylint: disable=bad-super-call
            super(ListSerializer, self).__init__(*args, **kwargs)

            self.child.bind(field_name='', parent=self) 
Example 2
Project: dynamic-rest   Author: AltSchool   File: metadata.py    License: MIT License 6 votes vote down vote up
def get_field_info(self, field):
        """Adds `related_to` and `nullable` to the metadata response."""
        field_info = OrderedDict()
        for attr in ('required', 'read_only', 'default', 'label'):
            field_info[attr] = getattr(field, attr)
        if field_info['default'] is empty:
            field_info['default'] = None
        if hasattr(field, 'immutable'):
            field_info['immutable'] = field.immutable
        field_info['nullable'] = field.allow_null
        if hasattr(field, 'choices'):
            field_info['choices'] = [
                {
                    'value': choice_value,
                    'display_name': force_text(choice_name, strings_only=True)
                }
                for choice_value, choice_name in field.choices.items()
            ]
        many = False
        if isinstance(field, DynamicRelationField):
            field = field.serializer
        if isinstance(field, ListSerializer):
            field = field.child
            many = True
        if isinstance(field, ModelSerializer):
            type = 'many' if many else 'one'
            field_info['related_to'] = field.get_plural_name()
        else:
            type = self.label_lookup[field]

        field_info['type'] = type
        return field_info 
Example 3
Project: dynamic-rest   Author: AltSchool   File: processors.py    License: MIT License 6 votes vote down vote up
def __init__(self, serializer, data):
        """Initializes and runs the processor.

        Arguments:
            serializer: a DREST serializer
            data: the serializer's representation
        """

        if isinstance(serializer, ListSerializer):
            serializer = serializer.child
        self.data = {}
        self.seen = defaultdict(set)
        self.plural_name = serializer.get_plural_name()
        self.name = serializer.get_name()

        # process the data, optionally sideloading
        self.process(data)

        # add the primary resource data into the response data
        resource_name = self.name if isinstance(
            data,
            dict
        ) else self.plural_name
        self.data[resource_name] = data 
Example 4
Project: edx-enterprise   Author: edx   File: serializers.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def to_internal_value(self, data):
        """
        This implements the same relevant logic as ListSerializer except that if one or more items fail validation,
        processing for other items that did not fail will continue.
        """

        if not isinstance(data, list):
            message = self.error_messages['not_a_list'].format(
                input_type=type(data).__name__
            )
            raise serializers.ValidationError({
                api_settings.NON_FIELD_ERRORS_KEY: [message]
            })

        ret = []

        for item in data:
            try:
                validated = self.child.run_validation(item)
            except serializers.ValidationError as exc:
                ret.append(exc.detail)
            else:
                ret.append(validated)

        return ret 
Example 5
Project: py2swagger   Author: Arello-Mobile   File: serializer.py    License: MIT License 5 votes vote down vote up
def __init__(self, serializer):
        """
        :param serializer: DjangoRestFramework Serializer
        """
        if isinstance(serializer, ListSerializer):
            serializer = serializer.child

        self.serializer = serializer
        self.name = self._get_name()

        self.fields = self._collect_fields() 
Example 6
Project: drf_tweaks   Author: HealthByRo   File: serializers.py    License: MIT License 5 votes vote down vote up
def __init__(self, field, parent, only_fields, include_fields):
        self.field = field
        self.parent = parent
        self.is_many = isinstance(field, serializers.ListSerializer) and isinstance(field.child, serializers.Serializer)
        self.has_context = isinstance(field, serializers.Serializer) or self.is_many
        if self.has_context:
            self.old_context = None
            self.only_fields = self.filter_fields(field.field_name, only_fields)
            self.include_fields = self.filter_fields(field.field_name, include_fields)
            self.on_exit_delete_fields = False
            self.on_exit_delete_include_fields = False
            self.old_fields = None
            self.old_include_fields = None 
Example 7
Project: dynamic-rest   Author: AltSchool   File: serializers.py    License: MIT License 5 votes vote down vote up
def __new__(cls, *args, **kwargs):
        """
        Custom constructor that sets the ListSerializer to
        DynamicListSerializer to avoid re-evaluating querysets.

        Addresses DRF 3.1.0 bug:
        https://github.com/tomchristie/django-rest-framework/issues/2704
        """
        meta = getattr(cls, 'Meta', None)
        if not meta:
            meta = type('Meta', (), {})
            cls.Meta = meta

        list_serializer_class = getattr(
            meta,
            'list_serializer_class',
            settings.LIST_SERIALIZER_CLASS or DynamicListSerializer
        )
        if not issubclass(list_serializer_class, DynamicListSerializer):
            list_serializer_class = DynamicListSerializer
        meta.list_serializer_class = list_serializer_class
        return super(
            WithDynamicSerializerMixin, cls
        ).__new__(
            cls, *args, **kwargs
        ) 
Example 8
Project: drf-json-api   Author: kevin-brown   File: utils.py    License: MIT License 5 votes vote down vote up
def get_related_field(field):
    if isinstance(field, ManyRelatedField):
        return field.child_relation

    if isinstance(field, ListSerializer):
        return field.child

    return field 
Example 9
Project: drf-json-api   Author: kevin-brown   File: utils.py    License: MIT License 5 votes vote down vote up
def is_related_many(field):
    if hasattr(field, "many"):
        return field.many

    if isinstance(field, ManyRelatedField):
        return True

    if isinstance(field, ListSerializer):
        return True

    return False 
Example 10
def data(self):
        return super(serializers.ListSerializer, self).data 
Example 11
Project: lexpredict-contraxsuite   Author: LexPredict   File: v1.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def data(self):
        # Note we deliberately return the super of ListSerializer to avoid
        # instantiating a ReturnList, which would force evaluating the generator
        return super(serializers.ListSerializer, self).data


# --------------------------------------------------------
# Document Note Views
# -------------------------------------------------------- 
Example 12
Project: GetTogether   Author: GetTogetherComm   File: views.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def data(self):
        ret = super(serializers.ListSerializer, self).data
        return ReturnDict(ret, serializer=self) 
Example 13
Project: BrewCenterAPI   Author: BrewCenter   File: styles.py    License: GNU General Public License v3.0 5 votes vote down vote up
def list(self, request):
        """
        Returns all the beer styles. Do not show suggested
        beer styles by default.
        """
        styles = models.Style.objects.all()
        if request.auth is None:
            styles = styles[:settings.UNAUTHENTICATED_RESULTS_COUNT]

        serializer = rf_serializers.ListSerializer(
            styles,
            child=serializers.SimpleStyleSerializer()
        )
        return Response(serializer.data) 
Example 14
Project: BrewCenterAPI   Author: BrewCenter   File: hops.py    License: GNU General Public License v3.0 5 votes vote down vote up
def list(self, request):
        """
        Returns all hop types in the system
        """
        serializer = rf_serializers.ListSerializer(
            models.HopType.objects.all() if request.auth is not None else models.HopType.objects.all()[:settings.UNAUTHENTICATED_RESULTS_COUNT],
            child=serializers.HopTypeSerializer()
        )
        return Response(serializer.data) 
Example 15
Project: BrewCenterAPI   Author: BrewCenter   File: hops.py    License: GNU General Public License v3.0 5 votes vote down vote up
def list(self, request):
        """
        Returns all hops that are approved in the system by default.
        """
        serializer = rf_serializers.ListSerializer(
            models.Hop.objects.all() if request.auth is not None else models.Hop.objects.all()[:settings.UNAUTHENTICATED_RESULTS_COUNT],
            child=serializers.SimpleHopSerializer()
        )
        return Response(serializer.data) 
Example 16
Project: BrewCenterAPI   Author: BrewCenter   File: countries.py    License: GNU General Public License v3.0 5 votes vote down vote up
def list(self, request):
        """
        Returns all countries in the system.
        """
        serializer = rf_serializers.ListSerializer(
            models.CountryCode.objects.all() if request.auth is not None else models.CountryCode.objects.all()[:settings.UNAUTHENTICATED_RESULTS_COUNT],
            child=serializers.CountryCodeSerializer()
        )
        return Response(serializer.data) 
Example 17
Project: BrewCenterAPI   Author: BrewCenter   File: suggestions.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get(self, request):
        """
        Returns all the suggestions.
        """
        serializer = rf_serializers.ListSerializer(models.Suggestion.objects.all(), child=serializers.SimpleSuggestionSerializer())
        return Response(serializer.data) 
Example 18
Project: BrewCenterAPI   Author: BrewCenter   File: fermentables.py    License: GNU General Public License v3.0 5 votes vote down vote up
def list(self, request):
        """
        Returns all fermentables that are approved in the system by default.
        """
        fermentables = models.Fermentable.objects.filter(is_active=True)

        if request.auth is None:
            fermentables = fermentables[:settings.UNAUTHENTICATED_RESULTS_COUNT]

        serializer = rf_serializers.ListSerializer(
            fermentables,
            child=serializers.Fermentable()
        )
        return Response(serializer.data) 
Example 19
Project: BrewCenterAPI   Author: BrewCenter   File: yeast.py    License: GNU General Public License v3.0 5 votes vote down vote up
def list(self, request):
        """
        Returns all approved yeast types by default.
        """
        serializer = rf_serializers.ListSerializer(
            models.YeastType.objects.all() if request.auth is not None else models.YeastType.objects.all()[:settings.UNAUTHENTICATED_RESULTS_COUNT],
            child=serializers.YeastTypeSerializer()
        )
        return Response(serializer.data) 
Example 20
Project: BrewCenterAPI   Author: BrewCenter   File: yeast.py    License: GNU General Public License v3.0 5 votes vote down vote up
def list(self, request):
        """
        Returns all approved yeast strains.
        """
        serializer = rf_serializers.ListSerializer(
            models.Yeast.objects.all() if request.auth is not None else models.Yeast.objects.all()[:settings.UNAUTHENTICATED_RESULTS_COUNT],
            child=serializers.SimpleYeastSerializer()
        )
        return Response(serializer.data) 
Example 21
Project: graphene-django   Author: graphql-python   File: serializer_converter.py    License: MIT License 5 votes vote down vote up
def convert_serializer_field(field, is_input=True, convert_choices_to_enum=True):
    """
    Converts a django rest frameworks field to a graphql field
    and marks the field as required if we are creating an input type
    and the field itself is required
    """

    if isinstance(field, serializers.ChoiceField) and not convert_choices_to_enum:
        graphql_type = graphene.String
    else:
        graphql_type = get_graphene_type_from_serializer_field(field)

    args = []
    kwargs = {"description": field.help_text, "required": is_input and field.required}

    # if it is a tuple or a list it means that we are returning
    # the graphql type and the child type
    if isinstance(graphql_type, (list, tuple)):
        kwargs["of_type"] = graphql_type[1]
        graphql_type = graphql_type[0]

    if isinstance(field, serializers.ModelSerializer):
        if is_input:
            graphql_type = convert_serializer_to_input_type(field.__class__)
        else:
            global_registry = get_global_registry()
            field_model = field.Meta.model
            args = [global_registry.get_type_for_model(field_model)]
    elif isinstance(field, serializers.ListSerializer):
        field = field.child
        if is_input:
            kwargs["of_type"] = convert_serializer_to_input_type(field.__class__)
        else:
            del kwargs["of_type"]
            global_registry = get_global_registry()
            field_model = field.Meta.model
            args = [global_registry.get_type_for_model(field_model)]

    return graphql_type(*args, **kwargs) 
Example 22
Project: ecommerce   Author: edx   File: serializers.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def to_internal_value(self, data):
        """
        This implements the same relevant logic as ListSerializer except that if one or more items fail validation,
        processing for other items that did not fail will continue.
        """

        if not isinstance(data, list):
            message = self.error_messages['not_a_list'].format(
                input_type=type(data).__name__
            )
            raise serializers.ValidationError({
                api_settings.NON_FIELD_ERRORS_KEY: [message]
            })

        ret = []

        for item in data:
            try:
                validated = self.child.run_validation(item)
            except serializers.ValidationError as exc:
                ret.append(
                    {
                        'non_field_errors': [{
                            'code': item.get('code'),
                            'email': item.get('email'),
                            'detail': 'failure',
                            'message': exc.detail['non_field_errors'][0]
                        }]
                    }
                )
            else:
                ret.append(validated)

        return ret 
Example 23
Project: aries-vcr   Author: bcgov   File: search.py    License: Apache License 2.0 5 votes vote down vote up
def data(self):
        ret = super(ListSerializer, self).data
        return ReturnDict(ret, serializer=self) 
Example 24
Project: open-humans   Author: OpenHumans   File: serializers.py    License: MIT License 5 votes vote down vote up
def to_representation(self, data):
        """
        List of object instances -> List of dicts of primitive datatypes.
        Overrides ListSerializer to add for checking for empty items.
        """
        # Dealing with nested relationships, data can be a Manager,
        # so, first get a queryset from the Manager if needed
        iterable = data.all() if isinstance(data, models.Manager) else data

        ret = []
        for item in iterable:
            repres = self.child.to_representation(item)
            if repres != OrderedDict():
                ret = ret + [repres]
        return ret 
Example 25
Project: indy-ssivc-tutorial   Author: IBM-Blockchain-Identity   File: search_serializers.py    License: Apache License 2.0 5 votes vote down vote up
def data(self):
    ret = super(ListSerializer, self).data
    return ReturnDict(ret, serializer=self) 
Example 26
Project: product-definition-center   Author: product-definition-center   File: renderers_serializers.py    License: MIT License 5 votes vote down vote up
def _get_field_type(serializer, field_name, field, include_read_only):
    """
    Try to describe a field type.
    """
    if not include_read_only and hasattr(field, 'writable_doc_format'):
        return _get_type_from_docstring(field.writable_doc_format)

    if hasattr(field, 'doc_format'):
        return _get_type_from_docstring(field.doc_format)

    if isinstance(field, (relations.ManyRelatedField, serializers.ListSerializer)):
        # Many field, recurse on child and make it a list
        if isinstance(field, relations.ManyRelatedField):
            field = field.child_relation
        else:
            field = field.child
        return [_get_field_type(serializer, field_name, field, include_read_only)]

    if field.__class__.__name__ in _SERIALIZER_DEFS:
        return _SERIALIZER_DEFS[field.__class__.__name__]

    if isinstance(field, serializers.SlugRelatedField):
        return _get_details_for_slug(serializer, field_name, field)

    if isinstance(field, serializers.SerializerMethodField):
        # For method fields try to use docstring of the method.
        method_name = field.method_name or 'get_{field_name}'.format(field_name=field_name)
        method = getattr(serializer, method_name, None)
        if method:
            docstring = getattr(method, '__doc__')
            return _get_type_from_docstring(docstring, docstring or 'method')

    if isinstance(field, serializers.BaseSerializer):
        return describe_serializer(field, include_read_only)

    logger = logging.getLogger(__name__)
    logger.error('Undocumented field %s' % field)
    return 'UNKNOWN' 
Example 27
Project: djangocms-rest-api   Author: divio   File: base.py    License: MIT License 5 votes vote down vote up
def many_init(cls, *args, **kwargs):
        kwargs['child'] = PageSerializer(*args, **kwargs)
        return ListSerializer(*args, **kwargs)


# TODO: decide if we need this 
Example 28
def data(self):
        return super(serializers.ListSerializer, self).data 
Example 29
Project: micromasters   Author: mitodl   File: views_test.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_patch_own_profile(self):
        """
        A user PATCHes their own profile
        """
        with mute_signals(post_save):
            ProfileFactory.create(user=self.user1, filled_out=False, agreed_to_terms_of_service=False)
        self.client.force_login(self.user1)

        with mute_signals(post_save):
            new_profile = ProfileFactory.create(filled_out=False)
        new_profile.user.social_auth.create(
            provider=EdxOrgOAuth2.name,
            uid="{}_edx".format(new_profile.user.username)
        )
        patch_data = ProfileSerializer(new_profile).data
        del patch_data['image']

        resp = self.client.patch(self.url1, content_type="application/json", data=json.dumps(patch_data))
        assert resp.status_code == 200

        old_profile = Profile.objects.get(user__username=self.user1.username)
        for key, value in patch_data.items():
            field = ProfileSerializer().fields[key]

            if isinstance(field, (ListSerializer, SerializerMethodField, ReadOnlyField)) or field.read_only is True:
                # these fields are readonly
                continue
            elif isinstance(field, DateField):
                assert getattr(old_profile, key) == parse(value).date()
            else:
                assert getattr(old_profile, key) == value 
Example 30
Project: micromasters   Author: mitodl   File: serializers_test.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def assert_required_fields(self, field_names, parent_getter, field_parent_getter):
        """
        Helper function to assert required fields
        """
        for key in field_names:
            field = field_parent_getter(ProfileFilledOutSerializer().fields)[key]
            is_generated = isinstance(field, (ListSerializer, SerializerMethodField, ReadOnlyField))
            is_skippable = (field.read_only or field.allow_null or field.allow_blank)
            # skip fields that are skippable, generated, read only, or that tie
            #  to other serializers which are tested elsewhere.
            if is_generated or is_skippable:
                continue

            clone = deepcopy(self.data)
            clone["image"] = self.profile.image
            clone["image_small"] = self.profile.image_small
            clone["image_medium"] = self.profile.image_medium
            parent_getter(clone)[key] = None
            with self.assertRaises(ValidationError) as ex:
                ProfileFilledOutSerializer(data=clone).is_valid(raise_exception=True)
            assert parent_getter(ex.exception.args[0]) == {key: ['This field may not be null.']}

            if isinstance(field, CharField):
                # test blank string too
                parent_getter(clone)[key] = ""
                with self.assertRaises(ValidationError) as ex:
                    ProfileFilledOutSerializer(data=clone).is_valid(raise_exception=True)
                assert parent_getter(ex.exception.args[0]) == {key: ['This field may not be blank.']}