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

标签 python django

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

这个值没有数据

>>> 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/

相关文章:

python - 如何对大文件应用单热编码?

python - 一旦我们的数据库变得太慢,我该如何创建按需报告?

python - 多选 Django 复选框表单验证

Django 测试 : determine which view was executed

python - 升级到 django 1.7 - 实例变为 unicode

python - + : 'DeferredAttribute' and 'str' 不受支持的操作数类型

Python Flask 电子邮件表单示例

python - 如何使用一个函数的输出作为另一个函数的输入

django - chromedriver.quit()之后的多个Chrome处理

Python 3.6 - 如何用文字翻译电话号码