-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
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_validate: exclude #8192
Comments
Could you use the |
Thanks for the reply @sydney-runkle. That seems to be for a different use case. #6861 explains the intent quite well.
fastapi's
(emphasis mine) |
@mustafa0x I had the same issue too and here is how I solved it. I used class RoleOrm(OrmBase):
__tablename__ = "roles"
# Columns
uid: Mapped[str] = mapped_column(
default=lambda: str(uuid4().hex),
primary_key=True,
index=True,
nullable=False,
unique=True,
)
# Relationships
role_permissions: Mapped[
list["RolePermissionOrm"] # noqa: F821 # type: ignore
] = relationship(cascade="all, delete-orphan", back_populates="role", lazy="joined") Role Model class Role(RoleBase, RoleBlame, RoleAutoGenerated):
role_permissions: list[RolePermission] | None = Field(
default=None,
description="The permissions that the role has",
) In Controller/Repository from fastapi import HTTPException
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import noload
class RoleRepository:
@staticmethod
async def get_by_uid(db: AsyncSession, uid: str) -> Role:
statement = select(RoleOrm).where(RoleOrm.uid == uid)
results = await db.execute(statement)
role_orm = results.unique().scalar_one_or_none()
if not role_orm:
raise HTTPException(
status_code=404,
detail="Role with given id does not exist",
)
role = Role.model_validate(role_orm)
return role
@staticmethod
async def get_many(
db: AsyncSession, skip: int = 0, limit: int = 20
) -> tuple[list[Role], str]:
count = await db.scalar(select(func.count(RoleOrm.uid)))
if not count:
return [], "0"
statement = (
select(RoleOrm)
.options(noload(RoleOrm.role_permissions))
.offset(skip)
.limit(limit)
)
results = await db.execute(statement)
roles = [Role.model_validate(orm) for orm in results.unique().scalars().all()]
return roles, str(count) The result on get_many now just gives me "role_permissions": [] |
Thanks @axelmukwena! It seems like that would work, but I prefer to not have to resort to that. I'm hoping pydantic v2 can add back this v1 feature. :) |
I really hope they add this one! I can't believe there's no standard way of handling this! |
+1 for this functionality! |
+1 |
+1 for this functionality! |
Initial Checks
Description
Lazy loaded orm fields are loaded inadvertently by model_validate. I'd like to be able to exclude fields from model_validate.
Previously discussed here #6861.
Affected Components
.model_dump()
and.model_dump_json()
model_construct()
, pickling, private attributes, ORM modeThe text was updated successfully, but these errors were encountered: