部分类型
Prisma Client Python 公开了在生成时基于模式定义的模型创建部分模型的接口。这在只有模型的某些字段可用或某些字段是可选/必需的情况下很有用。
部分模型被生成到 prisma.partials
。
查看 配置 以获取配置详细信息,以及 参考 以获取 API 文档。
示例
给定以下模型和部分类型生成器
model User {
id String @default(cuid()) @id
name String
posts Post[]
email String?
profile Profile?
}
prisma/partial_types.py
from prisma.models import User
# user with only email and name
User.create_partial('UserInLogin', include={'email', 'name'})
# user with a non-optional email field
User.create_partial('UserWithEmail', required={'email'})
# normal user model without an email
User.create_partial('UserWithoutEmail', exclude={'email'})
# user with a non-optional profile
User.create_partial('UserWithProfile', required={'profile'})
# user with an optional name
User.create_partial('UserWithOptionalName', optional={'name'})
# user without any relational fields (in this case without the profile and posts fields)
User.create_partial('UserWithoutRelations', exclude_relational_fields=True)
将生成以下部分类型
class UserInLogin(BaseModel):
name: str
email: Optional[str]
class UserWithEmail(BaseModel):
id: str
name: str
email: str
posts: Optional[List[models.Post]]
profile: Optional[models.Profile]
class UserWithoutEmail(BaseModel):
id: str
name: str
posts: Optional[List[models.Post]]
profile: Optional[models.Profile]
class UserWithProfile(BaseModel):
id: str
name: str
email: Optional[str]
posts: Optional[List[models.Post]]
profile: models.Profile
class UserWithOptionalName(BaseModel):
id: str
name: Optional[str]
email: Optional[str]
posts: Optional[List[models.Post]]
profile: Optional[models.Profile]
class UserWithoutRelations(BaseModel):
id: str
name: str
email: Optional[str]
示例用法
就像普通的 Prisma 模型一样,部分模型可以在任何接受 pydantic BaseModel 的地方使用。
部分类型特别有用的一个场景是在 FastAPI 端点中
from typing import Optional
from prisma import Prisma
from prisma.partials import UserWithoutRelations
from fastapi import FastAPI, Depends
from .utils import get_db
app = FastAPI()
@app.get(
'/users/{user_id}',
response_model=UserWithoutRelations,
)
async def get_user(user_id: str, db: Prisma = Depends(get_db)) -> Optional[User]:
return await db.user.find_unique(where={'id': user_id})
或者用于使原始查询类型安全
from prisma.partials import UserInLogin
user = await db.query_first(
'SELECT name, email FROM User WHERE id = ?',
'abc',
model=UserInLogin,
)
if user is None:
print('Did not find user')
else:
print(f'Found user: name={user.name}, email={user.email}')