Comments (2)
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.
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)
- "in-congruent" format validation behavior when exported to jsonschema HOT 1
- Failed to create model with two generic parameters when Typevar.default is set
- Discriminator on non-Union types HOT 1
- Write new feature pattern docs HOT 1
- `AnyUrl` requires host for validation but `.host` is typed `None | str` HOT 1
- Increase tests coverage for new pipeline API HOT 2
- `model_json_schema()` fails to include annotated third-party types: "Default value is not JSON serializable [non-serializable-default]" HOT 1
- Dynamically include/exclude fields from dumps HOT 1
- `TypeAdapter` with Union has `Any` type hint argument starting with Pydantic 2.7.0+ HOT 4
- "NameError: name 'T' is not defined" when using "from __future__ import annotations" with generic function HOT 3
- Allow schema() to respect PlainSerializer annotations to fully enable using Enum names HOT 1
- `include` and `exclude` are not passed to field serializer contexts HOT 3
- @field_validator not working when wrapped with @classmethod HOT 1
- Attributes declared as iterables are replaced in the instances by `pydantic-core` `ValidatorIterator` instance HOT 2
- Unable to validate deep JSON data HOT 1
- Spurious detections of cyclic references HOT 2
- ValidationError when using Generic constructor for subfield HOT 2
- Set reusable field validator directly on Field HOT 1
- TypeAdapter for collections.abc.MutableMapping fails when validate_python called on a collections.UserDict in strict mode HOT 4
- Enum and min_length Validation HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from pydantic.