我的数据库中有一个用户模型。用户可以拥有“recommended_profile”列表,这是我数据库中的另一个对象。 当用户触发获取端点时,我想显示“recommended_profile”的第一个元素,而不是列表的全部。
请参阅下面的我的模型和架构:
class User_Wallet_Recommended(Timestamp,Base) :
__tablename__ = "users_wallet_recommended"
id = Column(Integer,primary_key=True)
user_id = Column(UUID(as_uuid=True),ForeignKey("users.id"), nullable=False)
owner = relationship("User", back_populates="recommended_profil", foreign_keys=[user_id])
class User(Timestamp,Base) :
__tablename__ = "users"
id = Column(UUID(as_uuid=True),primary_key=True,default=uuid.uuid4)
hashed_password = Column(String, nullable=False)
first_name = Column(String(30), nullable=False)
last_name = Column(String(30), nullable=False)
email = Column(EmailType, unique=True,index=True,nullable=False)
recommended_profil = relationship("User_Wallet_Recommended", back_populates="owner")
class User(UserBase):
model_config = ConfigDict(from_attributes=True)
id: UUID
...
recommended_profil : User_Wallet_Recommended_Out | None = None
无法检索 User_Wallet_Recommended_Out 的单个元素,因为我有一个列表......
一种方法是使用
@field_validator
:
from uuid import uuid4, UUID
from pydantic import BaseModel, ConfigDict, field_validator
class User_Wallet_Recommended_Out(BaseModel):
id: UUID
class UserBase(BaseModel):
pass
class User(UserBase):
model_config = ConfigDict(from_attributes=True)
id: UUID
recommended_profil : User_Wallet_Recommended_Out | None = None
@field_validator("recommended_profil", mode="before")
@classmethod
def serialize_recomended_profil(cls, recomended_profil):
if len(recomended_profil):
return recomended_profil[0]
else:
return None
u = User.model_validate({"id": uuid4(), "recommended_profil": [{"id": uuid4()}, {"id": uuid4()}]})
print(u.model_dump())
u2 = User.model_validate({"id": uuid4(), "recommended_profil": []})
print(u2.model_dump())
输出:
{'id': UUID('f60af8b5-286c-4a05-bcc6-33ab52e1af4a'), 'recommended_profil': {'id': UUID('acadcbe5-205f-4579-b69f-da281182ff22')}}
{'id': UUID('c673b440-5e05-4d39-967e-4592b3105340'), 'recommended_profil': None}