本文整理汇总了Python中rest_framework.serializers.IntegerField方法的典型用法代码示例。如果您正苦于以下问题:Python serializers.IntegerField方法的具体用法?Python serializers.IntegerField怎么用?Python serializers.IntegerField使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rest_framework.serializers
的用法示例。
在下文中一共展示了serializers.IntegerField方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import IntegerField [as 别名]
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
示例2: test_pagination_multiple_datatypes
# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import IntegerField [as 别名]
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)]
)
}
示例3: drf_router
# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import IntegerField [as 别名]
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
示例4: test_describe_fields
# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import IntegerField [as 别名]
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'}
})
示例5: test_validation_attrs
# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import IntegerField [as 别名]
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
))
示例6: test_pagination
# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import IntegerField [as 别名]
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)]
}
示例7: get_false_annotations_queryset
# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import IntegerField [as 别名]
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
示例8: get_distinct_count
# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import IntegerField [as 别名]
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)
示例9: test_no_source_on_child
# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import IntegerField [as 别名]
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."
)
示例10: test_should_integer_convert_int
# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import IntegerField [as 别名]
def test_should_integer_convert_int():
assert_conversion(serializers.IntegerField, graphene.Int)
示例11: test_should_list_convert_to_list
# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import IntegerField [as 别名]
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
示例12: _get_hits_order
# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import IntegerField [as 别名]
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
示例13: generate_fileds
# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import IntegerField [as 别名]
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
示例14: __init__
# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import IntegerField [as 别名]
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
示例15: get_count
# 需要导入模块: from rest_framework import serializers [as 别名]
# 或者: from rest_framework.serializers import IntegerField [as 别名]
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)