gpt4 book ai didi

python - 如何将空查询集指定为非空查询集 : [ ] to []

转载 作者:行者123 更新时间:2023-12-05 08:35:12 25 4
gpt4 key购买 nike

我在确定一个对象是否为空时遇到问题...这是我的代码:

这个值没有数据

>>> x = Booking.objects.filter(date_select='2011-12-3')
>>> print x
[]
>>> if x == None:
... print 'none'
...
>>>

这有一个数据:

>>> x = Booking.objects.filter(date_select='2011-12-2')
>>> print x
[<Booking: arab>, <Booking: arab>, <Booking: vvv>]
>>> if x == None:
... print 'none'
...
>>>

我从上一个问题中了解到 [] 不等于 None...这是我想在我的代码中应用的算法:

if x has an empty queryset
print empy
else
print data

谁能帮我解决这个问题?谢谢...

最佳答案

使用exists()

Returns True if the QuerySet contains any results, and False if not. This tries to perform the query in the simplest and fastest way possible, but it does execute nearly the same query. This means that calling QuerySet.exists() is faster than bool(some_query_set), but not by a large degree.

if my_queryset.exists():
print "QuerySet has Data"
else:
print "QuerySet is empty"

关于python - 如何将空查询集指定为非空查询集 : [ ] to [<object: hi>],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8365255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com