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

OpenAPI复用Schema作为请求体时如何移除Entity属性

复用Schema并排除Entity属性实现请求体的方案

根据你使用的技术栈,以下是几种无需重复代码即可排除Entity属性的实现方式:

OpenAPI/Swagger 场景

方式1:使用allOf + not关键字

通过组合引用Address Schema并排除指定的Entity属性,同时移除继承的必填约束:

components:
  schemas:
    Entity:
      type: object
      properties:
        id: { type: string }
        created: { type: string, format: date-time }
        modified: { type: string, format: date-time }
      required: [id, created, modified]
    Address:
      allOf:
        - $ref: '#/components/schemas/Entity'
        - type: object
          properties:
            street: { type: string }
            city: { type: string }
            zipCode: { type: string }
          required: [street, city, zipCode]
    CreateAddress:
      allOf:
        - $ref: '#/components/schemas/Address'
        - not:
            properties:
              id: {}
              created: {}
              modified: {}
          required: [] # 清除继承自Entity的必填项

方式2:使用omitProperties(OpenAPI 3.1+)

OpenAPI 3.1版本开始支持直接排除指定属性,写法更简洁:

components:
  schemas:
    CreateAddress:
      type: object
      $ref: '#/components/schemas/Address'
      omitProperties: [id, created, modified]

TypeScript(NestJS/TypeORM 场景)

类型层面复用

利用TypeScript内置的Omit工具类型直接生成请求体类型:

class Entity {
  id: string;
  created: Date;
  modified: Date;
}

class Address extends Entity {
  street: string;
  city: string;
  zipCode: string;
}

// 排除Entity的三个属性,生成CreateAddress类型
type CreateAddressDto = Omit<Address, 'id' | 'created' | 'modified'>;

NestJS 专用方案

使用@nestjs/mapped-types提供的OmitType工具类,自动生成排除指定属性的DTO类:

import { OmitType } from '@nestjs/mapped-types';

export class Address extends Entity {
  street: string;
  city: string;
  zipCode: string;
}

// 生成移除指定属性的CreateAddressDto
export class CreateAddressDto extends OmitType(Address, ['id', 'created', 'modified'] as const) {}

Python(Pydantic 场景)

继承并配置排除字段

通过继承Address类,在Config中指定需要排除的字段:

from pydantic import BaseModel

class Entity(BaseModel):
    id: str
    created: str
    modified: str

class Address(Entity):
    street: str
    city: str
    zip_code: str

class CreateAddress(Address):
    class Config:
        exclude = {'id', 'created', 'modified'}

动态生成模型(Pydantic v2+)

使用TypeAdapter结合Omit类型,快速生成排除指定属性的模型:

from typing import Omit
from pydantic import TypeAdapter

# 基于Address排除Entity属性生成CreateAddress模型
CreateAddress = TypeAdapter(Omit[Address, 'id' | 'created' | 'modified']).py_model

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 11:45:32