Skip to content

Bug: PydanticDTO issues #4232

@gsakkis

Description

@gsakkis

Description

Several issues when deserializing into DTOData Pydantic models:

  • default_factory is ignored: such field values are apparently set to None instead of the default_factory() value. Attempting to create an instance with data.create_instance() fails if the fields are not nullable.
  • Inconsistent behavior between a field annotated as str | None vs SomeModel | None: data.as_builtins() sets the former to None but it doesn't set the latter at all.
  • Nullable fields (T | None) and optional nullable fields (T | None = None) are treated the same: the former should raise an error if the field is missing instead of defaulting to None.

URL to code causing the issue

No response

MCVE

from typing import Any
from uuid import UUID

from litestar import Litestar, post
from litestar.dto import DTOConfig, DTOData
from litestar.plugins.pydantic import PydanticDTO
from pydantic import BaseModel, Field


class Address(BaseModel):
    street: str = ""
    city: str = ""
    state: str = ""
    zip: str = ""


class User(BaseModel):
    id: UUID
    name: str

    nullable_password: str | None
    nullable_address: Address | None
    optional_password: str | None = None
    optional_address: Address | None = None
    passwords: list[str] = Field(default_factory=list)
    addresses: list[Address] = Field(default_factory=list)


class UserDTO(PydanticDTO[User]):
    config = DTOConfig(exclude={"id"})


@post("/users", dto=UserDTO, sync_to_thread=False)
def create_user(data: DTOData[User]) -> dict[str, Any]:
    # data.create_instance(id=uuid4())
    print(data.as_builtins())
    return data.as_builtins()


app = Litestar(route_handlers=[create_user])

Steps to reproduce

$ http --unsorted --body localhost:8000/users name=john
{
    "name": "john",
    "nullable_password": null,
    "optional_password": null,
    "passwords": null,
    "addresses": null
}

Screenshots

No response

Logs


Litestar Version

2.16.0

Platform

  • Linux
  • Mac
  • Windows
  • Other (Please specify in the description above)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Bug 🐛This is something that is not working as expected

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions