Giter Site home page Giter Site logo

Comments (2)

pablofueros avatar pablofueros commented on June 18, 2024 1

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!

from pydantic.

sydney-runkle avatar sydney-runkle commented on June 18, 2024

@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!

from pydantic.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.