Skip to content

need DATETIME_FORMAT to ninja Schema #1451

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

Open
LeonemZhang opened this issue Apr 18, 2025 · 6 comments
Open

need DATETIME_FORMAT to ninja Schema #1451

LeonemZhang opened this issue Apr 18, 2025 · 6 comments

Comments

@LeonemZhang
Copy link

I hope to add a global configuration to modify the format of the datetime return

@LeonemZhang
Copy link
Author

LeonemZhang commented Apr 18, 2025

django-ninja>=1.4.1,
django==5.2,
pydantic==2.11.3,

from pydantic import Field

class DatetimeSchema(Schema):
    create_time: datetime = Field(
        default=datetime.now(),
        examples=[datetime.now()],
    )
    update_time: datetime = Field(
        default=datetime.now(),
        examples=[datetime.now()],
    )

    @staticmethod
    def resolve_create_time(obj):
        return str(obj.create_time.strftime("%Y-%m-%d %H:%M:%S"))

    @staticmethod
    def resolve_update_time(obj):
        return str(obj.update_time.strftime("%Y-%m-%d %H:%M:%S"))

class CustomSchema(DatetimeSchema):
    ...
json result
        "create_time": "2025-04-18T02:57:03",
        "update_time": "2025-04-18T02:57:03",

@LeonemZhang
Copy link
Author

LeonemZhang commented Apr 18, 2025

from ninja import Schema

class DatetimeSchema(Schema):
    class Config(Schema.Config):
        json_encoders = {
            datetime: lambda dt: dt.strftime("%Y-%m-%d %H:%M:%S")
        }


class CustomSchema(DatetimeSchema):
    ...
json result
   "create_time": "2025-04-18T02:57:03.313Z",
   "update_time": "2025-04-18T02:57:03.313Z"

@LeonemZhang
Copy link
Author

from pydantic import BaseModel

class DatetimeSchema(BaseModel):
    class Config:
        json_encoders = {
            datetime: lambda dt: dt.strftime("%Y-%m-%d %H:%M:%S")
        }
error:

ERROR:root:1 validation error for NinjaResponseSchema
response.items.0
  Input should be a valid dictionary or instance of FileDetailResp [type=model_type, input_value=<SysFile: 测试数据.pdf>, input_type=SysFile]
    For further information visit https://errors.pydantic.dev/2.11/v/model_type

@vitalik
Copy link
Owner

vitalik commented Apr 18, 2025

@LeonemZhang you can apply global json encoder for all dates/datetimes like this:

from ninja.renderers import JSONRenderer
from ninja.responses import NinjaJSONEncoder


class JsonEncoder(NinjaJSONEncoder):

    def default(self, o):
        if isinstance(o, datetime):
            return o.strftime('%Y-%m-%dT%H:%M:%S')
        return super().default(o)


class CustomJsonRender(JsonRenderer):
    encoder_class = JsonEncoder

...

api = NinjaAPI(renderer=CustomJsonRender())

@LeonemZhang
Copy link
Author

Thanks, it works
but I can't find BaseJsonRenderer, I use from ninja.renderers import JSONRenderer instead
Perhaps we can update this configuration method in the documentation?

@vitalik
Copy link
Owner

vitalik commented Apr 23, 2025

@LeonemZhang yes - JSONRenderer is the one!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants