Python rest_framework.serializers.IntegerField() Examples

The following are 22 code examples for showing how to use rest_framework.serializers.IntegerField(). 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
Project: opencraft   Author: open-craft   File: serializers.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        """
        Start with empty serializer and add fields from both theme schemas
        """
        super().__init__(*args, **kwargs)

        # We're just going to use the v1 theme schema here since v0 is
        # getting deprecated soon
        theme_schema_combined = {
            **theme_schema_v1['properties']
        }
        for key, value in theme_schema_combined.items():
            field_type = None
            if key == 'version':
                field_type = serializers.IntegerField(required=False)
            elif value == ref('flag'):
                field_type = serializers.BooleanField(required=False)
            else:
                field_type = serializers.CharField(
                    max_length=7,
                    required=False,
                    allow_blank=True,
                    # TODO: Add a color validator here
                )
            self.fields[key] = field_type 
Example 2
Project: cadasta-platform   Author: Cadasta   File: test_pagination.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_pagination_multiple_datatypes(self):
        req = self._get_request('/foo', {'limit': 10, 'offset': 20})
        qs1 = [{'id': i} for i in range(25)]
        qs2 = [{'name': i} for i in range(25)]

        class FakeSerializer1(serializers.Serializer):
            id = serializers.IntegerField()

        class FakeSerializer2(serializers.Serializer):
            name = serializers.IntegerField()

        resp = paginate_results(
            req, (qs1, FakeSerializer1), (qs2, FakeSerializer2))
        assert resp == {
            'count': 50,
            'next': 'http://nxt',
            'previous': 'http://prv',
            'results': (
                [{'id': 20+i} for i in range(5)] +
                [{'name': i} for i in range(5)]
            )
        } 
Example 3
Project: scout_apm_python   Author: scoutapp   File: django_app.py    License: MIT License 6 votes vote down vote up
def drf_router():
    """
    DRF Router as a lazy object because it needs to import User model which
    can't be done until after django.setup()
    """
    from django.contrib.auth.models import User
    from rest_framework import routers
    from rest_framework import serializers
    from rest_framework import viewsets

    class UserSerializer(serializers.Serializer):
        id = serializers.IntegerField(label="ID", read_only=True)
        username = serializers.CharField(max_length=200)

    class UserViewSet(viewsets.ModelViewSet):
        queryset = User.objects.all()
        serializer_class = UserSerializer

    router = routers.SimpleRouter()
    router.register(r"users", UserViewSet)
    return router 
Example 4
Project: product-definition-center   Author: product-definition-center   File: tests.py    License: MIT License 6 votes vote down vote up
def test_describe_fields(self):
        class DummySerializer(serializers.Serializer):
            str = serializers.CharField()
            int = serializers.IntegerField()

        instance = DummySerializer()

        result = describe_serializer(instance, include_read_only=False)
        self.assertEqual(_flatten_field_data(result), {
            'str': {'value': 'string'},
            'int': {'value': 'int'}
        })

        result = describe_serializer(instance, include_read_only=True)
        self.assertEqual(_flatten_field_data(result), {
            'str': {'value': 'string'},
            'int': {'value': 'int'}
        }) 
Example 5
Project: drf-schema-adapter   Author: drf-forms   File: test_unit.py    License: MIT License 6 votes vote down vote up
def test_validation_attrs(self):
        data = (
            (CharField(), {}),
            (IntegerField, {}),
            (CharField(min_length=3), {'min': 3}),
            (CharField(max_length=10), {'max': 10}),
            (CharField(min_length=3, max_length=10), {'min': 3, 'max': 10}),
            (IntegerField(min_value=0), {'min': 0}),
            (IntegerField(max_value=100), {'max': 100}),
            (IntegerField(min_value=0, max_value=100), {'min': 0, 'max': 100}),
        )

        for input_field, expected in data:
            result = utils.get_field_dict.get_validation_attrs(input_field)
            self.assertEqual(result, expected,
                             'got {} while expecting {} when comparing validation attrs for {}'.format(
                                 result,
                                 expected,
                                 input_field
                             )) 
Example 6
Project: opencraft   Author: open-craft   File: serializers.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        """
        Add fields dynamically from the schema.
        """
        super().__init__(*args, **kwargs)
        static_content_overrides = {
            **static_content_overrides_v0_schema['properties']
        }

        for key, _ in static_content_overrides.items():
            if key == 'version':
                field_type = serializers.IntegerField(required=False)
            else:
                field_type = serializers.CharField(required=False, allow_blank=True)
            self.fields[key] = field_type 
Example 7
Project: cadasta-platform   Author: Cadasta   File: test_pagination.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_pagination(self):
        req = self._get_request('/foo', {'limit': 10, 'offset': 20})
        qs = [{'id': i} for i in range(50)]

        class FakeSerializer(serializers.Serializer):
            id = serializers.IntegerField()

        assert paginate_results(req, (qs, FakeSerializer)) == {
            'count': 50,
            'next': 'http://nxt',
            'previous': 'http://prv',
            'results': [{'id': 20+i} for i in range(10)]
        } 
Example 8
Project: lexpredict-contraxsuite   Author: LexPredict   File: v1.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def get_false_annotations_queryset(self):
        """
        Get FieldAnnotationFalseMatch queryset
        """
        false_ann_qs = self.get_initial_queryset(FieldAnnotationFalseMatch)

        # TODO: move common annotations into get_initial_queryset()
        # WARN: fields order makes sense here for list view
        false_ann_qs = false_ann_qs.values(*self.common_fields).annotate(
            status_id=Value(FieldAnnotationStatus.rejected_status_pk(), output_field=IntegerField()),
            modified_by_id=Value(None, output_field=CharField()),
            modified_date=Value(None, output_field=DateField()),

            document_id=Cast('document_id', output_field=CharField()),
            project_id=F('document__project_id'),
            project_name=F('document__project__name'),
            document_name=F('document__name'),
            document_status=F('document__status__name'),
            field_name=F('field__title'),
            status_name=Value('Rejected', output_field=CharField()),
            assignee_name=Case(When(Q(assignee__name__isnull=False) & ~Q(assignee__name=''), then=F('assignee__name')),
                               When(assignee__first_name__isnull=False,
                                    assignee__last_name__isnull=False,
                                    then=Concat(F('assignee__first_name'), Value(' '), F('assignee__last_name'))),
                               default=F('assignee__username'),
                               output_field=CharField()
                               )
        )
        return false_ann_qs 
Example 9
def get_distinct_count(self, instance):
        """ Return the distinct count for this facet."""
        # The instance is expected to be formatted as a three tuple containing the field name, normal count and
        # distinct count. This is consistent with the superclass implementation here:
        # https://github.com/inonit/drf-haystack/blob/master/drf_haystack/serializers.py#L321
        count = instance[2]
        return serializers.IntegerField(read_only=True).to_representation(count) 
Example 10
def get_distinct_count(self, instance):
        """ Return the distinct count for this facet."""
        count = instance['distinct_count']
        return serializers.IntegerField(read_only=True).to_representation(count) 
Example 11
Project: drf-extra-fields   Author: Hipo   File: test_fields.py    License: Apache License 2.0 5 votes vote down vote up
def test_no_source_on_child(self):
        with pytest.raises(AssertionError) as exc_info:
            IntegerRangeField(child=serializers.IntegerField(source='other'))

        assert str(exc_info.value) == (
            "The `source` argument is not meaningful when applied to a `child=` field. "
            "Remove `source=` from the field declaration."
        ) 
Example 12
Project: drf-extra-fields   Author: Hipo   File: test_fields.py    License: Apache License 2.0 5 votes vote down vote up
def test_no_source_on_child(self):
        with pytest.raises(AssertionError) as exc_info:
            FloatRangeField(child=serializers.IntegerField(source='other'))

        assert str(exc_info.value) == (
            "The `source` argument is not meaningful when applied to a `child=` field. "
            "Remove `source=` from the field declaration."
        ) 
Example 13
Project: drf-extra-fields   Author: Hipo   File: test_fields.py    License: Apache License 2.0 5 votes vote down vote up
def test_no_source_on_child(self):
        with pytest.raises(AssertionError) as exc_info:
            DateTimeRangeField(child=serializers.IntegerField(source='other'))

        assert str(exc_info.value) == (
            "The `source` argument is not meaningful when applied to a `child=` field. "
            "Remove `source=` from the field declaration."
        ) 
Example 14
Project: drf-extra-fields   Author: Hipo   File: test_fields.py    License: Apache License 2.0 5 votes vote down vote up
def test_no_source_on_child(self):
        with pytest.raises(AssertionError) as exc_info:
            DateRangeField(child=serializers.IntegerField(source='other'))

        assert str(exc_info.value) == (
            "The `source` argument is not meaningful when applied to a `child=` field. "
            "Remove `source=` from the field declaration."
        ) 
Example 15
Project: graphene-django   Author: graphql-python   File: test_field_converter.py    License: MIT License 5 votes vote down vote up
def test_should_integer_convert_int():
    assert_conversion(serializers.IntegerField, graphene.Int) 
Example 16
Project: graphene-django   Author: graphql-python   File: test_field_converter.py    License: MIT License 5 votes vote down vote up
def test_should_list_convert_to_list():
    class StringListField(serializers.ListField):
        child = serializers.CharField()

    field_a = assert_conversion(
        serializers.ListField,
        graphene.List,
        child=serializers.IntegerField(min_value=0, max_value=100),
    )

    assert field_a.of_type == graphene.Int

    field_b = assert_conversion(StringListField, graphene.List)

    assert field_b.of_type == graphene.String 
Example 17
Project: scirius   Author: StamusNetworks   File: rest_api.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _get_hits_order(self, request, order):
        try:
            result = ESTopRules(request).get(count=Rule.objects.count(), order=order)
        except ESError:
            queryset = Rule.objects.order_by('sid')
            queryset = queryset.annotate(hits=models.Value(0, output_field=models.IntegerField()))
            queryset = queryset.annotate(hits=models.ExpressionWrapper(models.Value(0), output_field=models.IntegerField()))
            return queryset.values_list('sid', 'hits')

        result = map(lambda x: (x['key'], x['doc_count']), result)
        return result 
Example 18
Project: polemarch   Author: vstconsulting   File: serializers.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def generate_fileds(ansible_reference: AnsibleArgumentsReference, ansible_type: str) -> OrderedDict:
    if ansible_type is None:
        return OrderedDict()  # nocv

    fields = OrderedDict()

    for ref, settings in ansible_reference.raw_dict[ansible_type].items():
        if ref in ['help', 'version', ]:
            continue
        ref_type = settings.get('type', None)
        kwargs = dict(help_text=settings.get('help', ''), required=False)
        field = None
        if ref_type is None:
            field = serializers.BooleanField
            kwargs['default'] = False
        elif ref_type == 'int':
            field = serializers.IntegerField
        elif ref_type == 'string' or 'choice':
            field = vst_fields.VSTCharField
            kwargs['allow_blank'] = True

        if ref == 'verbose':
            field = serializers.IntegerField
            kwargs.update(dict(max_value=4, default=0))
        if ref in models.PeriodicTask.HIDDEN_VARS:
            field = vst_fields.SecretFileInString
        if ref == 'inventory':
            kwargs['autocomplete'] = 'Inventory'
            field = InventoryAutoCompletionField

        if field is None:  # nocv
            continue

        if ansible_type == 'module':
            if ref == 'group':
                kwargs['default'] = 'all'

        field_name = ref.replace('-', '_')
        fields[field_name] = field(**kwargs)

    return fields 
Example 19
Project: pydantic   Author: samuelcolvin   File: test_drf.py    License: MIT License 5 votes vote down vote up
def __init__(self, allow_extra):
        class Model(serializers.Serializer):
            id = serializers.IntegerField()
            client_name = serializers.CharField(max_length=255, trim_whitespace=False)
            sort_index = serializers.FloatField()
            # client_email = serializers.EmailField(required=False, allow_null=True)
            client_phone = serializers.CharField(max_length=255, trim_whitespace=False, required=False, allow_null=True)

            class Location(serializers.Serializer):
                latitude = serializers.FloatField(required=False, allow_null=True)
                longitude = serializers.FloatField(required=False, allow_null=True)
            location = Location(required=False, allow_null=True)

            contractor = serializers.IntegerField(required=False, allow_null=True, min_value=0)
            upstream_http_referrer = serializers.CharField(
                max_length=1023, trim_whitespace=False, required=False, allow_null=True
            )
            grecaptcha_response = serializers.CharField(min_length=20, max_length=1000, trim_whitespace=False)
            last_updated = serializers.DateTimeField(required=False, allow_null=True)

            class Skill(serializers.Serializer):
                subject = serializers.CharField()
                subject_id = serializers.IntegerField()
                category = serializers.CharField()
                qual_level = serializers.CharField()
                qual_level_id = serializers.IntegerField()
                qual_level_ranking = serializers.FloatField(default=0)
            skills = serializers.ListField(child=Skill())

        self.allow_extra = allow_extra  # unused
        self.serializer = Model 
Example 20
Project: drf-haystack   Author: rhblind   File: serializers.py    License: MIT License 5 votes vote down vote up
def get_count(self, instance):
        """
        Haystack facets are returned as a two-tuple (value, count).
        The count field should contain the faceted count.
        """
        instance = instance[1]
        return serializers.IntegerField(read_only=True).to_representation(instance) 
Example 21
Project: drf-haystack   Author: rhblind   File: test_serializers.py    License: MIT License 5 votes vote down vote up
def test_serializer_get_fields(self):
        obj = SearchQuerySet().filter(lastname="Foreman")[0]
        serializer = self.serializer1(instance=obj)
        fields = serializer.get_fields()

        self.assertIsInstance(fields, dict)
        self.assertIsInstance(fields["integer_field"], IntegerField)
        self.assertIsInstance(fields["text"], CharField)
        self.assertIsInstance(fields["firstname"], CharField)
        self.assertIsInstance(fields["lastname"], CharField)
        self.assertIsInstance(fields["autocomplete"], CharField) 
Example 22
Project: drf-haystack   Author: rhblind   File: test_serializers.py    License: MIT License 4 votes vote down vote up
def setUp(self):
        MockPersonIndex().reindex()
        MockPetIndex().reindex()

        class Serializer1(HaystackSerializer):

            integer_field = serializers.IntegerField()
            city = serializers.SerializerMethodField()

            class Meta:
                index_classes = [MockPersonIndex]
                fields = ["text", "firstname", "lastname", "autocomplete"]

            def get_integer_field(self, instance):
                return 1

            def get_city(self, instance):
                return "Declared overriding field"

        class Serializer2(HaystackSerializer):

            class Meta:
                index_classes = [MockPersonIndex]
                exclude = ["firstname"]

        class Serializer3(HaystackSerializer):

            class Meta:
                index_classes = [MockPersonIndex]
                fields = ["text", "firstname", "lastname", "autocomplete"]
                ignore_fields = ["autocomplete"]

        class Serializer7(HaystackSerializer):

            class Meta:
                index_classes = [MockPetIndex]

        class ViewSet1(HaystackViewSet):
            serializer_class = Serializer1

            class Meta:
                index_models = [MockPerson]

        self.serializer1 = Serializer1
        self.serializer2 = Serializer2
        self.serializer3 = Serializer3
        self.serializer7 = Serializer7
        self.view1 = ViewSet1