Django检查是否存在查询 [英] Django check for any exists for a query
问题描述
在Django中如何检查查询是否存在任何条目
In django how to check whether any entry exists for a query
sc=scorm.objects.filter(Header__id=qp.id)
这是在php中完成的方式
This was how it was done in php
if(mysql_num_rows($resultn)) {
// True condition
}
else {
// False condition
}
推荐答案
使用 count()
:
sc=scorm.objects.filter(Header__id=qp.id)
if sc.count() > 0:
...
相对于 len()
表示尚未对QuerySet求值:
The advantage over e.g. len()
is, that the QuerySet is not yet evaluated:
count()
在幕后执行SELECT COUNT(*)
,因此您应始终使用count ()
,而不是将所有记录加载到Python对象中并在结果上调用len()
。
count()
performs aSELECT COUNT(*)
behind the scenes, so you should always usecount()
rather than loading all of the record into Python objects and callinglen()
on the result.
请记住, 对QuerySet进行评估 值得一读。
Having this in mind, When QuerySets are evaluated can be worth reading.
如果使用 get()
,例如 scorm.objects.get(pk = someid)
,并且对象不存在,引发 ObjectDoesNotExist
异常:
If you use get()
, e.g. scorm.objects.get(pk=someid)
, and the object does not exists, an ObjectDoesNotExist
exception is raised:
from django.core.exceptions import ObjectDoesNotExist
try:
sc = scorm.objects.get(pk=someid)
except ObjectDoesNotExist:
print ...
更新:
,也可以使用 存在()
:
if scorm.objects.filter(Header__id=qp.id).exists():
....
如果QuerySet包含任何结果,则返回
True
,否则返回False
。这会尝试以最简单,最快的方式执行查询,但是它执行的查询与普通QuerySet查询几乎相同。
Returns
True
if the QuerySet contains any results, andFalse
if not. This tries to perform the query in the simplest and fastest way possible, but it does execute nearly the same query as a normal QuerySet query.
这篇关于Django检查是否存在查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!