如何在Django QuerySet中使用Python类型提示? [英] How to use Python type hints with Django QuerySet?

查看:140
本文介绍了如何在Django QuerySet中使用Python类型提示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用Python类型提示在Django QuerySet中指定记录类型?像 QuerySet [SomeModel] 这样的东西?

Is it possible to specify type of records in Django QuerySet with Python type hints? Something like QuerySet[SomeModel]?

例如,我们有模型:

class SomeModel(models.Model):
    smth = models.IntegerField()

我们想将该模型的QuerySet传递为func中的参数:

And we want to pass QuerySet of that model as param in func:

def somefunc(rows: QuerySet):
    pass

但是如何指定类型QuerySet中的记录,例如 List [SomeModel]

But how to specify type of records in QuerySet, like with List[SomeModel]:

def somefunc(rows: List[SomeModel]):
    pass

但使用QuerySet吗?

but with QuerySet?

推荐答案

一种解决方案可能是使用联合键入类。

One solution may be using Union typing class.

from typing import Union, List
from django.db.models import QuerySet
from my_app.models import MyModel

def somefunc(row: Union[QuerySet, List[MyModel]]):
    pass

现在,当对<$ c $进行切片时c> row 参数i t将知道返回的类型是MyModel的另一个列表还是MyModel的实例,同时还暗示<$ c $ QuerySet 类的方法在<$ c $上可用c> row 个参数。

Now when you slice the row argument it will know that the returned type is either another list of MyModel or an instance of MyModel, whilst also hinting that the methods of the QuerySet class are available on the row argument too.

这篇关于如何在Django QuerySet中使用Python类型提示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆