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

如何为Django模型实例对象设置函数参数类型提示?

Django模型实例的类型提示方案

直接用你的Device模型类作为类型提示就可以,因为Device.objects.get()返回的就是该类的实例:

from inventory.models import Device

def do_something(device: Device) -> bool:
    if device.id:
        # some_logic
        return True

特殊场景的处理

  • 如果函数接收的实例可能为None(比如使用get_object_or_404之外的方法,存在查询不到的情况),可以用Optional来标记:
from typing import Optional
from inventory.models import Device

def do_something(device: Optional[Device]) -> bool:
    if device and device.id:
        # some_logic
        return True
    return False
  • 如果需要处理QuerySet类型(比如传入多个Device实例的集合),可以用QuerySet[Device],不过这个需要安装django-stubs来让类型检查工具(如mypy)正确识别:
from django.db.models.query import QuerySet
from inventory.models import Device

def process_devices(devices: QuerySet[Device]) -> list[bool]:
    return [device.id is not None for device in devices]

额外提示

安装django-stubs后,类型检查工具还能识别Django模型自带的属性(比如id、created_at等),避免出现类型警告,安装命令:

pip install django-stubs

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 14:30:41