Skip to content

Conversation

@henrybetts
Copy link
Contributor

Currently when encoding a model, the json_encoders property is ignored if it is defined in a superclass of the model. For example;

from pydantic import BaseModel
from datetime import datetime, timezone
from fastapi.encoders import jsonable_encoder


class ModelWithCustomEncoder(BaseModel):
    class Config:
        json_encoders = {
            datetime: lambda dt: dt.replace(
                microsecond=0, tzinfo=timezone.utc
            ).isoformat()
        }


class ModelWithCustomEncoderSubclass(ModelWithCustomEncoder):
    dt_field: datetime

    class Config:
        pass


model = ModelWithCustomEncoderSubclass(dt_field=datetime(2019, 1, 1, 8))

print(model.json())
# {"dt_field": "2019-01-01T08:00:00+00:00"}

print(jsonable_encoder(model))
# {'dt_field': '2019-01-01T08:00:00'}

To fix this, I modified jsonable_encoder to get the config using the .__config__ property.

@codecov
Copy link

codecov bot commented Jul 22, 2020

Codecov Report

Merging #1769 into master will not change coverage.
The diff coverage is 100.00%.

Impacted file tree graph

@@            Coverage Diff            @@
##            master     #1769   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files          235       235           
  Lines         6989      6995    +6     
=========================================
+ Hits          6989      6995    +6     
Impacted Files Coverage Δ
fastapi/encoders.py 100.00% <100.00%> (ø)
tests/test_jsonable_encoder.py 100.00% <100.00%> (ø)

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update a63b1ef...53e1185. Read the comment docs.

@github-actions
Copy link
Contributor

📝 Docs preview for commit 53e1185 at: https://5f183a82083ba939380c4c42--fastapi.netlify.app

@tiangolo tiangolo merged commit 7fbe373 into fastapi:master Aug 3, 2020
@tiangolo
Copy link
Member

tiangolo commented Aug 3, 2020

Excellent, thank you! 🚀 🎉

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

Successfully merging this pull request may close these issues.

2 participants