FastAPI结合SQLAlchemy Utils的Country类型与Pydantic序列化问题求助
FastAPI结合SQLAlchemy Utils的Country类型与Pydantic序列化问题求助
我正在用FastAPI搭建一个简单后端,想使用SQLAlchemy Utils提供的Country类型,但遇到了序列化相关的问题,麻烦各位帮忙看看!
以下是我的代码片段:
schemas.py
from pydantic import BaseModel from typing import Any, List class UserBase(BaseModel): email: str email_bis : str country : Any class UserCreate(UserBase): password: str class User(UserBase): id: int is_active: bool items: list[Item] = [] class Config: from_attributes = True
models.py
from sqlalchemy import Column, Integer, String, Boolean from sqlalchemy.ext.declarative import Base from sqlalchemy.orm import relationship from sqlalchemy_utils import CountryType class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True, index=True) email = Column(String, unique=True, index=True) email_bis = Column(String, unique=True, index=True) hashed_password = Column(String) is_active = Column(Boolean, default=True) country = Column(CountryType) items = relationship("Item", back_populates="owner")
创建用户的API处理函数
def create_user(db: Session, user: schemas.UserCreate): fake_hashed_password = user.password + "notreallyhashed" db_user = models.User( email=user.email, email_bis=user.email_bis, hashed_password=fake_hashed_password, country=Country(user.country) ) db.add(db_user) db.commit() db.refresh(db_user) return db_user
我尝试了多种方式来适配Country类型,但最后碰到的错误提示是:
pydantic_core._pydantic_core.PydanticSerializationError: Unable to serialize unknown type: <class 'sqlalchemy_utils.primitives.country.Country'>
有没有大佬能给我指点一下解决方法呀?
备注:内容来源于stack exchange,提问作者Gillibo
相关产品推荐
相关产品推荐

