Skip to content
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

Open
4 of 13 tasks
pablofueros opened this issue May 13, 2024 · 2 comments
Open
4 of 13 tasks

model_dump include/exclude attributes by alias #9428

pablofueros opened this issue May 13, 2024 · 2 comments

Comments

@pablofueros
Copy link

Initial Checks

  • I have searched Google & GitHub for similar requests and couldn't find anything
  • I have read and followed the docs and still think this feature is missing

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 tried populate_by_name and loc_by_alias options of the ConfigDict but didnt work.

Affected Components

@sydney-runkle
Copy link
Member

@pablofueros,

Currently, you can't exclude attributes via their aliases. I don't see this as a priority for us in the short term - could you please provide a reproducible example explaining your use case? Thanks!

@pablofueros
Copy link
Author

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 have some functions to get data from an api. My idea was to save that data in some middle point (pydantic models) before filling some sqlachemy tables (as I have to do some data transformation).
  • The thing is that one of the pydantic models has to populate more than one sql table.
  • The fields I want to get on each table are passed to the model_dump method of the pydantic model, but im using aliases (camel_case to snake_case conversion).

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 ConfigDict or in the model_dump() to alow this use case.

Greetings!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants