Python rest_framework.serializers.ListSerializer() Examples

The following are 30 code examples of rest_framework.serializers.ListSerializer(). 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 also want to check out all available functions/classes of the module rest_framework.serializers , or try the search function .
Example #1
Source File: fields.py    From django-rest-serializer-field-permissions with GNU General Public License v3.0 7 votes vote down vote up
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
Source File: metadata.py    From dynamic-rest with MIT License 7 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
Source File: serializer.py    From py2swagger with MIT License 6 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 #4
Source File: processors.py    From dynamic-rest with 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 #5
Source File: serializers.py    From edx-enterprise with 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 #6
Source File: yeast.py    From BrewCenterAPI with 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 #7
Source File: suggestions.py    From BrewCenterAPI with 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 #8
Source File: yeast.py    From BrewCenterAPI with 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 #9
Source File: serializer_converter.py    From graphene-django with 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 #10
Source File: serializers.py    From ecommerce with 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 #11
Source File: search.py    From aries-vcr with Apache License 2.0 5 votes vote down vote up
def data(self):
        ret = super(ListSerializer, self).data
        return ReturnDict(ret, serializer=self) 
Example #12
Source File: serializers.py    From open-humans with 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 #13
Source File: search_serializers.py    From indy-ssivc-tutorial with Apache License 2.0 5 votes vote down vote up
def data(self):
    ret = super(ListSerializer, self).data
    return ReturnDict(ret, serializer=self) 
Example #14
Source File: renderers_serializers.py    From product-definition-center with 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 #15
Source File: base.py    From djangocms-rest-api with 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 #16
Source File: serializers.py    From openwisp-network-topology with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def data(self):
        return super(serializers.ListSerializer, self).data 
Example #17
Source File: views_test.py    From micromasters with 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 #18
Source File: serializers_test.py    From micromasters with 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.']} 
Example #19
Source File: serializers.py    From django-netjsongraph with MIT License 5 votes vote down vote up
def data(self):
        return super(serializers.ListSerializer, self).data 
Example #20
Source File: fermentables.py    From BrewCenterAPI with 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 #21
Source File: countries.py    From BrewCenterAPI with 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 #22
Source File: hops.py    From BrewCenterAPI with 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 #23
Source File: hops.py    From BrewCenterAPI with 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 #24
Source File: styles.py    From BrewCenterAPI with 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 #25
Source File: views.py    From GetTogether with 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 #26
Source File: v1.py    From lexpredict-contraxsuite with 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 #27
Source File: serializers.py    From django-spillway with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def data(self):
        return super(serializers.ListSerializer, self).data 
Example #28
Source File: utils.py    From drf-json-api with 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 #29
Source File: utils.py    From drf-json-api with 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 #30
Source File: serializers.py    From dynamic-rest with 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
        )