New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add strict option to fields.Integer #667

Merged
merged 3 commits into from Aug 20, 2017

Conversation

Projects
None yet
2 participants
@yoichi
Contributor

yoichi commented Aug 10, 2017

I want a feature to get validation error on float and Decimal value for fields.Integer instead of rounding it to integer.
Compare with #231, we already have tests expecting current rounding behaviour, so I've added a constructor option 'strict' and keep the default behavior.

before the change

from marshmallow import fields
from marshmallow import Schema

DATA = {'foo': '3.0', 'bar': 3.14, 'baz': 3.0}

class MySchema(Schema):
    foo = fields.Integer(required=True)
    bar = fields.Integer(required=True)
    baz = fields.Integer(required=True)

s = MySchema()
print('--- Marshmallow ---')
print(s.validate(DATA))


from django.conf import settings
settings.configure(INSTALLED_APPS=['rest_framework'])
import django
django.setup()

from rest_framework import serializers as ser

class MySer(ser.Serializer):
    foo = ser.IntegerField()
    bar = ser.IntegerField()
    baz = ser.IntegerField()

ser = MySer(data=DATA)
ser.is_valid()
print('--- DRF ---')
print(ser.errors)
--- Marshmallow ---
{'foo': ['Not a valid integer.']}
--- DRF ---
{'bar': ['A valid integer is required.']}

after the change

from marshmallow import fields
from marshmallow import Schema

DATA = {'foo': '3.0', 'bar': 3.14, 'baz': 3.0}

class MySchema(Schema):
    foo = fields.Integer(required=True, strict=True)
    bar = fields.Integer(required=True, strict=True)
    baz = fields.Integer(required=True, strict=True)

s = MySchema()
print('--- Marshmallow ---')
print(s.validate(DATA))
--- Marshmallow ---
{'baz': ['Not a valid integer.'], 'bar': ['Not a valid integer.'], 'foo': ['Not a valid integer.']}
Add strict option to fields.Integer
cause validation error instead of rounding float and Decimal
@sloria

This comment has been minimized.

Member

sloria commented Aug 17, 2017

Thanks! Seems like a good feature. @yoichi Can you please add yourself to AUTHORS.rst?

yoichi added some commits Aug 18, 2017

Merge branch 'dev' into strict-integer
Conflicts:
	AUTHORS.rst

@sloria sloria merged commit e4a3059 into marshmallow-code:dev Aug 20, 2017

1 check passed

continuous-integration/travis-ci/pr The Travis CI build passed
Details
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment