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

如何用抽象模型模拟EmptyQuerySet适配drf-spectacular?

解决无模型场景下drf-spectacular的EmptyQuerySet需求问题

在使用ListAPIView对接第三方API且无对应Django模型时,drf-spectacular生成OpenAPI规范需要返回EmptyQuerySet,抽象模型因无管理器无法满足需求,可通过以下几种方式解决:

方案一:创建非托管(Unmanaged)模型

创建普通模型但设置managed=False,Django不会为其生成数据库表,但会提供模型管理器,可正常返回objects.none():

from django.db import models

class Invoice(models.Model):
    # 定义与InvoiceSerializer对应的字段(可选,仅为文档生成提供结构)
    id = models.CharField(max_length=255)
    amount = models.DecimalField(max_digits=10, decimal_places=2)
    status = models.CharField(max_length=50)
    # 其他需要的字段...

    class Meta:
        managed = False  # 禁用数据库表创建
        db_table = 'dummy_invoice'  # 虚拟表名,无实际作用

视图中返回空QuerySet:

def get_queryset(self):
    if getattr(self, 'swagger_fake_view', False):
        return Invoice.objects.none()
  
    return StripeWrapper().get_invoices()

方案二:使用drf-spectacular装饰器指定响应结构

通过@extend_schema直接定义响应的序列化器,跳过drf-spectacular对queryset的依赖,此时返回空列表即可满足fake视图需求:

from drf_spectacular.utils import extend_schema

@extend_schema(responses=InvoiceSerializer(many=True))
class InvoicesList(generics.ListAPIView):
    serializer_class = InvoiceSerializer

    def get_queryset(self):
        if getattr(self, 'swagger_fake_view', False):
            return []
        
        return StripeWrapper().get_invoices()

方案三:手动构造EmptyQuerySet

若不想创建模型,可直接导入EmptyQuerySet并返回,部分版本可能需要绑定模型,若报错优先选用前两种方案:

from django.db.models.query import EmptyQuerySet

def get_queryset(self):
    if getattr(self, 'swagger_fake_view', False):
        return EmptyQuerySet()
  
    return StripeWrapper().get_invoices()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 09:52:50