Output of python -c "import pydantic.utils; print(pydantic.utils.version_info())":
pydantic version: 1.5.1
pydantic compiled: False
install path: [home]/repos/fastapi-test/.venv/lib/python3.8/site-packages/pydantic
python version: 3.8.2 (default, Apr 8 2020, 14:31:25) [GCC 9.3.0]
Hello!
I'm currently developing an API using FastAPI, and, by extension, Pydantic.
There are a few fields which require dynamic default values, e.g. created_date, and per https://github.com/samuelcolvin/pydantic/issues/866 I've been using default_factory to do so. However, when a field has a default value defined using a factory, the dynamic value shows up in the generated JSON schema, which might not be desirable?
Example:
from datetime import datetime, timezone
from uuid import uuid4
from pydantic import BaseModel, Field
class SchemaTest(BaseModel):
uuid = Field(default_factory=uuid4)
created_date: datetime = Field(
default_factory=lambda: datetime.now(timezone.utc)
)
print(SchemaTest.schema_json(indent=2))
The above outputs
{
"title": "SchemaTest",
"type": "object",
"properties": {
"created_date": {
"title": "Created Date",
"default": "2020-05-15T10:04:18.692173+00:00",
"type": "string",
"format": "date-time"
},
"uuid": {
"title": "Uuid",
"default": "79a35356-4619-49da-9bbe-4be75a696485",
"type": "string",
"format": "uuid"
}
}
}
These values are of course different each time the schema is generated.
I understand why it happens, but I'm not sure it's entirely correct to expose the value in the JSON schema like this. It's worth noting that this is not a problem when using the "old" method of setting defaults via a validator.
Please let me know if I'm missing something, or that this is indeed appropriate behavior. Thanks for developing such a great tool!
You can probably give it a note in the description= that this is dynamically generated to be the current datetime, and the default is only an example of the output.
Hello @jnik-aarhus !
I don't see how #1504 would fix this?
@samuelcolvin Because of this line where I set default as None instead of calling the default_factory. But I need to have a look at your answer
Most helpful comment
Hello @jnik-aarhus !
1504 should also solve your issue.