You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.21 10:39:34