This question is probably opinion based but since I don't master the libraries I prefer to ask. I'm working with SQLAlchemy FastAPI and Pydantic.
For a given entity, is it possible/good-practice to have multiple dtos ?
Let's put some context: We have a user table that contains these rows: email (PK), username, password, firstname, lastname.
We have the associated SQLAlchemy class:
class User(Base):
__tablename__ = "user_account"
email: Mapped[str] = mapped_column(String(60), primary_key=True)
username: Mapped[str] = mapped_column(String(30))
password: Mapped[str] = mapped_column(String(60))
firstname: Mapped[str] = mapped_column(String(30))
lastname: Mapped[str] = mapped_column(String(30))
address= relationship("Address", cascade="all, delete-orphan", backref="user_account", lazy="joined")
As you can see we have a relationship with the Address table.
Laslty, we have the User DTO for pydantic
class UserDTO(BaseModel):
email: str
username: str
password: str
firstname: str
lastname: str
The issue is simple. The first use case is a registration; using fastapi and pydantic we can get the json body as an isntance of the UserDTO class. Then SQLAlchemy does the insert without problem.
Now let's say I want to get a user with his Address data.
If I update my UserDTO this way:
class User(BaseModel):
email: str
username: str
password: str
firstname: str
lastname: str
address: list[something] | None = None
Then my registration service doesn't work because SQLAlchemy doesn't accept the extra "address" field.
So my question is: how do we use DTOs in this case? Do I need multiple UserDTO class for different use cases ? or is there another way to do this?