master
๋ธ๋์น์ ๋ํด ์กด์ฌํ๋์ง ํ์ธํ์ต๋๋ค.ISO-8601 ํ์์ ๋ ์ง / ์๊ฐ ์ง๋ ฌํ ๊ตฌํ์ ์ฝ๋๋ฒ ์ด์ค์์ ์ผ๊ด๋์ง ์์ต๋๋ค.
https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/fields.py#L1094 ๋ง์ดํฌ๋ก ์ด๋ ์ง๋ ฌํ ๋ ๊ฐ์ ํฌํจ๋ฉ๋๋ค.
https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/utils/encoders.py#L30 ์์๋ ๋ฐ๋ฆฌ ์ด ๋ง
์ผ๊ด๋ ๊ตฌํ์ ๊ธฐ๋ํฉ๋๋ค.
ํด๋น ์์
ํ์ฌ ๋ด API์ ์ผ๋ถ ํด๋ผ์ด์ธํธ์๋ ๋ฐ๋ฆฌ ์ด ์ ๋ฐ๋์ ๋ ์ง๊ฐ ํ์ํ๋ฉฐ ๋ง์ดํฌ๋ก ์ด๋ฅผ ์ฒ๋ฆฌ ํ ์ โโ์์ต๋๋ค. DRF 3.3 ์ค์ ์์ 'DATETIME_FORMAT'์ None์ผ๋ก ์ค์ ํ์ฌ์ด๋ฅผ ๋ฌ์ฑํ์ต๋๋ค. 3.4๋ก ์ ๊ทธ๋ ์ด๋ํ๋ฉด์ด ๋์์ด ์ค๋จ๋ฉ๋๋ค. ์ด์ ๋์์ ์ฝ๊ฒ ์ป์ ์์๋ ๋ฐฉ๋ฒ์ด ์์ต๋๊น? ECMA-262 ํ์์ ์ ๊ณตํ๋ datetime ํ์ ๋ฌธ์์ด์ ์ง์ ํ๋ ๋ฐฉ๋ฒ์ ์์๋ผ ์ ์์ต๋๋ค. ๊ฐ์ฌ.
@georgejlee ์ฌ์ฉ์ ์ง์ ๋ ๋๋ฌ๋ฅผ ์ฌ์ฉ
import datetime
from rest_framework.renderers import JSONRenderer
from rest_framework.utils.encoders import JSONEncoder
class MilliSecondEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
representation = obj.isoformat()
if obj.microsecond:
representation = representation[:23] + representation[26:]
if representation.endswith('+00:00'):
representation = representation[:-6] + 'Z'
return representation
else:
return super().default(obj)
class JSONRenderer(JSONRenderer):
encoder_class = MilliSecondEncoder
ํ , DEFAULT_RENDERER_CLASSES๋ฅผ ์ปค์คํ ๋ ๋๋ฌ๋ก ๋ณ๊ฒฝํด๋ ๋ทฐ์ ์ ๋ ๋๋ง์ ์ํฅ์์ฃผ์ง ์์์ต๋๋ค. renderer_class๋ฅผ ๋ช ์ ์ ์ผ๋ก ์ค์ ํด์ผํ์ต๋๋ค.
encoder_class
๋ํด datetime
encoder_class
๋ฅผ ํตํด ์ฌ์ฉ์ ์ง์ ์ธ์ฝ๋๋ฅผ ์ฌ์ฉํ๋๋ก DRF๋ฅผ ๊ตฌ์ฑํ๋ ค๊ณ ์๋ํ๋ ๋์ ๋ค๋ฅธ ์ฌ๋์ด์ด ๋ฌธ์ ๋ฅผ ๋ฐ๊ฒฌํ๋ ๊ฒฝ์ฐ. https://github.com/encode/django-rest-framework/issues/4255#issuecomment -234560555์ ์๋ฃจ์
์ด ๋๋ฅผ ์ํด ์ผํ์ง ๋ชปํ๊ฒ ํ ๋ฌธ์ ๋ DRF๊ฐ ํ๋์ DateTimeField
์๋ ํ ๋ด์ฅ ์ธ์ฝ๋๋ฅผ ์ฌ์ฉํ๋ค๋ ๊ฒ์
๋๋ค. format
kwarg๊ฐ None
์ค์ ๋์ด ์๊ฑฐ๋ DateTimeField
serializer๋ฅผ ์ง์ ํ์ง ์์ ๊ฒฝ์ฐ REST_FRAMEWORK
์ ๊ตฌ์ฑ์ ์ค์ ํด์ผํฉ๋๋ค. DEFAULT_FORMAT: None
์์ settings.py
๊ทธ๋์ผ๋ง custom encoder
๊ฐ ์ฌ์ฉ๋ฉ๋๋ค.
๊ทธ ์ด์ ๋ ์ฌ์ฉ์ ์ ์ Renderer
๋ฅผ ์ฌ์ฉํ์ฌ datetime
๋ฅผ ๋ ๋๋ง ํ๊ธฐ ์ ์ serializer ํ๋ (๋๋ ๊ธฐ๋ณธ ํ๋ ๋ ๋๋ฌ)๊ฐ Response
ํ์์ ์ง์ ํ๋ ๋ฐ ์ฌ์ฉ๋๊ธฐ ๋๋ฌธ์
๋๋ค. ๋ฐ๋ผ์ datetime ํ๋๋ ์ด๋ฏธ ๋ฌธ์์ด์ด๊ณ ๊ธฐ๋ณธ Python ์ ํ์ด ์ธ์ฝ๋์ ์ํด ์ฒ๋ฆฌ๋๋ฏ๋ก ์ฌ์ฉ์ ์ง์ ์ธ์ฝ๋์ default
๋ฉ์๋๊ฐ ํธ์ถ๋์ง ์์ผ๋ฏ๋ก ๊ธฐ๋ณธ JSONEncoder๊ฐ ์ฌ์ฉ์ ์ง์ ์ธ์ฝ๋๋ฅผ ํธ์ถํ์ง ์์ต๋๋ค.
๊ฐ์ฅ ์ ์ฉํ ๋๊ธ
@georgejlee ์ฌ์ฉ์ ์ง์ ๋ ๋๋ฌ๋ฅผ ์ฌ์ฉ
ํ , DEFAULT_RENDERER_CLASSES๋ฅผ ์ปค์คํ ๋ ๋๋ฌ๋ก ๋ณ๊ฒฝํด๋ ๋ทฐ์ ์ ๋ ๋๋ง์ ์ํฅ์์ฃผ์ง ์์์ต๋๋ค. renderer_class๋ฅผ ๋ช ์ ์ ์ผ๋ก ์ค์ ํด์ผํ์ต๋๋ค.