-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
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
model_dump include/exclude attributes by alias #9428
Comments
Currently, you can't |
Hi @sydney-runkle thank you for the answer. I came across this while builing an aplication, ill try to explain myself as best I can.
I'll try to replicate it on the following example: from typing import List, Self
from pydantic import AliasGenerator, BaseModel, ConfigDict, Field
from pydantic.alias_generators import to_snake
from sqlalchemy import ForeignKey
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
class Schema(BaseModel):
model_config = ConfigDict(
alias_generator=AliasGenerator(
serialization_alias=to_snake,
),
)
class MyModel(Schema):
address: str
postalCode: str
info: str
num: int
userName: str = Field(serialization_alias="name")
userCode: str = Field(serialization_alias="code")
# Some field_serializers / computed_fields ...
class Base(DeclarativeBase):
@classmethod
def column_keys(cls) -> set[str]:
return {col.key for col in cls.__table__.columns}
@classmethod
def from_api(cls, source: Schema) -> Self:
data = source.model_dump(
include=cls.column_keys(),
by_alias=True,
)
return cls(**data)
class Location(Base):
__tablename__ = "location"
id: Mapped[int] = mapped_column(primary_key=True)
address: Mapped[str]
postal_code: Mapped[str]
objects: Mapped[List["MyObject"]] = relationship(back_populates="location")
class User(Base):
__tablename__ = "user"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
code: Mapped[str]
objects: Mapped[List["MyObject"]] = relationship(back_populates="user")
class MyObject(Base):
__tablename__ = "my_table"
id: Mapped[int] = mapped_column(primary_key=True)
info: Mapped[str]
num: Mapped[int]
location_id = mapped_column(ForeignKey("location.id"))
user_id = mapped_column(ForeignKey("user.id"))
location: Mapped[Location] = relationship(back_populates="objects")
user: Mapped[User] = relationship(back_populates="objects") I suggest to add an option either in the Greetings! |
Initial Checks
Description
Hi, I have a problem for which I have not found a solution.
I need to extract info from a pydentic model using
model_dump
. Is there any way to find the attributes to include/exclude by aliases? I have triedpopulate_by_name
andloc_by_alias
options of theConfigDict
but didnt work.Affected Components
.model_dump()
and.model_dump_json()
model_construct()
, pickling, private attributes, ORM modeThe text was updated successfully, but these errors were encountered: