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

在Django+FastAPI中创建Order时如何使用不同Pydantic模型

问题解决步骤

错误根源

你的代码存在两个核心问题:

  1. Django get_or_create 用法错误——直接传入Pydantic对象而非关键字参数,且返回了元组而非实际ORM实例
  2. Pydantic无法从返回的元组中解析出ORM模型字段,导致所有字段校验失败

修复代码

1. 修正views.py中的create_order函数

from uuid import UUID
from . import models, schemas

def create_order(order: schemas.OrderBase):
    # 将Pydantic模型转为字典,以关键字参数传递给get_or_create
    new_order, _ = models.Order.objects.get_or_create(**order.dict())
    # 返回实际的Django ORM实例,而非get_or_create返回的元组
    return new_order

注:get_or_create返回(实例, 是否新建)的元组,我们只需要第一个元素,用_忽略第二个返回值。

2. 适配Pydantic版本(可选)

如果使用Pydantic v2,需要将schemas.py中的orm_mode替换为from_attributes:

from uuid import UUID
from pydantic import BaseModel

class OrderBase(BaseModel):
    product: str
    period: str
    power: int
    side: str

    class Config:
        from_attributes = True  # Pydantic v2替代orm_mode的配置

class OrderResponse(OrderBase):
    id: UUID

如果是Pydantic v1,原有的orm_mode = True无需修改。

验证逻辑

  • 创建接口接收OrderBase模型的请求体,无需传入id,符合创建阶段需求
  • 返回时FastAPI会自动用OrderResponse模型序列化Django ORM实例,自动包含生成的id字段

内容的提问来源于stack exchange,提问作者JSRB

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 19:15:31