我在确定一个对象是否为空时遇到问题... 这是我的代码:
这个值没有数据
>>> 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/