是否有一个Django函数来计算对象,即使没有对象?

2024-10-01 15:38:48 发布

您现在位置:Python中文网/ 问答频道 /正文

是否有Django内置函数返回queryset中的项数,如果对象为None,则返回0?你知道吗

我期望的是:

thefunction([obj1, obj2])
>>> 2
obj1 = None
thefunction(obj1)
>>> 0

我尝试了len()python函数和count()Django方法,但它们对None对象不起作用(我理解这种行为)。你知道吗

如果没有这样的方法,我会自己写,只是不想重新发明轮子。你知道吗

EDIT:我自己写的,但是我仍然想知道(学习)这个函数在Python中是否存在:)

def len_none(iterable):
    ''' Return the len of an object, and 0 if object is None or empty '''
    if iterable: # object exists and is not empty
        return len(iterable)
    else:
        return 0

谢谢!你知道吗


Tags: and对象django方法函数nonelenreturn
2条回答

对queryset调用len将返回0(如果它是空的)。对于空的queryset,queryset不会返回None。例如,如果我有5个图像:

>>> len(Images.objects.none()) == 0
True
>>> len(Images.objects.all()) == 5
True

我不认为有什么可以做的具体你要求的,但有很多方法来实现它。这里有一个:

>>> one = [1, 2, 3]
>>> two = None
>>> len(one or [])
3
>>> len(two or [])
0

你可以自己写:

def my_count(var):
    try:
        return count(var)
    except TypeError:
        return 0

相关问题 更多 >

    热门问题