๋ ํฐ ์๋ ๋ DecimalField
์ ํจ์ฑ ๊ฒ์ฌ์ ์คํจํ์ง ์์ต๋๋ค.
์๋ฅผ ๋ค์ด:
>>> serializers.DecimalField(max_digits=3, decimal_places=1).run_validation(200000000000.0)
>>> Decimal('2E+11')
๊ทธ ์ซ์๊ฐ 3์๋ฆฌ ์ด์์ด๋ฏ๋ก ValidationError
๊ฐ ๋ฐ์ํ ๊ฒ์ผ๋ก ์์ํฉ๋๋ค. Django์ ์์ ์ ํจ์ฑ ๊ฒ์ฌ์์ ์์ ์ค๋ฅ๊ฐ ๋ฐ์ํฉ๋๋ค.
>>> forms.DecimalField(max_digits=3, decimal_places=1).clean(200000000000.0)
ValidationError: [u'Ensure that there are no more than 3 digits in total.']
์์ ์ํ ์
๋ ฅ์์ 0์ ์ญ์ ํ๋ฉด ValidationError
๊ฐ ๋ฐ์ํฉ๋๋ค.
>>> serializers.DecimalField(max_digits=3, decimal_places=1).run_validation(20000000000.0)
ValidationError: [u'Ensure that there are no more than 3 digits in total.']
๋ง์ฐฌ๊ฐ์ง๋ก ์๋ ๋ฒํธ๋ฅผ ์ฌ์ฉํ์ฌ Decimal
๋ฐ int๋ก ์์ธ๊ฐ ๋ฐ์ํฉ๋๋ค.
>>> serializers.DecimalField(max_digits=3, decimal_places=1).run_validation(200000000000)
ValidationError: [u'Ensure that there are no more than 3 digits in total.']
>>> serializers.DecimalField(max_digits=3, decimal_places=1).run_validation(Decimal('200000000000.0'))
ValidationError: [u'Ensure that there are no more than 3 digits in total.']
์ต๊ทผ์ https://github.com/tomchristie/django-rest-framework/pull/2948 ์์ ํต์ฌ ๋ผ์ธ์ด ๋ณ๊ฒฝ๋์์ง๋ง ์ ํํ์ง ์๊ณ Django์ forms.DecimalField
์ ํจ์ฑ ๊ฒ์ฌ์์ ๋ฒ์ด๋ ๋ณต์ฌ๋ ๊ฒ์ผ๋ก ๋ณด์
๋๋ค. ๊ทธ๋๋ก:
decimals = exponent * decimal.Decimal(-1) if exponent < 0 else 0
#2948์์ ์ธ๊ธ๋ ์๋ ๋ฌธ์ ๋ฅผ ์ ๋ง ์ดํดํ์ง ๋ชปํด์ ์ค์ด ์ ๋ฐ๋์๋์ง ๋ชจ๋ฅด๊ฒ ์ต๋๋ค. ์๋ ๋ฌธ์ ๋ฅผ ์ดํดํ๊ณ ์๋ค๋ฉด ๊ธฐ๊บผ์ด ๋ฌธ์ ๋ฅผ ํด๊ฒฐํด ๋๋ฆฌ๊ฒ ์ต๋๋ค.
๋ค์์ ํ ์คํธ์ ์คํจํ ํจ์น์ ๋๋ค.
diff --git a/tests/test_fields.py b/tests/test_fields.py
index 0427873..cf41a5b 100644
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -773,6 +773,7 @@ class TestDecimalField(FieldValues):
(Decimal('Nan'), ["A valid number is required."]),
(Decimal('Inf'), ["A valid number is required."]),
('12.345', ["Ensure that there are no more than 3 digits in total."]),
+ (200000000000.0, ["Ensure that there are no more than 3 digits in total."]),
('0.01', ["Ensure that there are no more than 1 decimal places."]),
(123, ["Ensure that there are no more than 2 digits before the decimal point."])
)
๊ณ ๋ง์ ๋ผ์ด์ธ.
์ด์ ํจ์ฌ ๋ ํฌ๋ช ํ๊ณ ๋ถ๋ช ํ ๋ ผ๋ฆฌ๋ก ํด๊ฒฐ๋์์ต๋๋ค.
@tomchristie @ryankask - 2015๋
์ ๋ฆด๋ฆฌ์ค ์ด์ ํ์ ์ถ๊ฐ๋ ๊ฒ์ ์ ์ ์์ต๋๋ค. 3.11.0
๋ฒ์ ์์ ์ฌ์ ํ ์ด ๋ฌธ์ ๋ฅผ ๊ฒช๊ณ ์์ต๋๋ค. ์์ ์ฌํญ์ด ๊ฒฐ๊ตญ ๋ฆด๋ฆฌ์ค ๋์์ต๋๊น? ์๋ ์ฝ๋:
class RecommendationSerializer(serializers.Serializer):
total_owed = serializers.DecimalField(decimal_places=2, max_digits=8, min_value='1.00',
rounding=ROUND_DOWN)
term_length = serializers.IntegerField(min_value=1)
class Meta:
fields = ['total_owed', 'term_length']
serializer = RecommendationSerializer(data={'total_owed': '12.333333333333333', 'term_length': 6})
serializer.is_valid(raise_exception=True)
>>> {"total_owed": ["Ensure that there are no more than 8 digits in total."]}
@Audace ์์๋๋ ์ ํจ์ฑ ๊ฒ์ฌ ์ค๋ฅ๊ฐ ๋ฐ์ํฉ๋๋ค. ํ ๋ก ๊ทธ๋ฃน ์ ์ด ํ ๋ก ๋ฐ ๊ธฐํ ์ฌ์ฉ ์ง๋ฌธ์ ํ๊ธฐ์ ๊ฐ์ฅ ์ข์ ์ฅ์์ ๋๋ค. ๊ฐ์ฌ!
๊ฐ์ฅ ์ ์ฉํ ๋๊ธ
์ด์ ํจ์ฌ ๋ ํฌ๋ช ํ๊ณ ๋ถ๋ช ํ ๋ ผ๋ฆฌ๋ก ํด๊ฒฐ๋์์ต๋๋ค.