sc=scorm.objects.filter(Header__id=qp.id)
if sc.count() > 0:
...
与len()相比,QuerySet的优势在于,它还没有被评估:
count() performs a SELECT COUNT(*) behind the scenes, so you should always use count() rather than loading all of the record into Python objects and calling len() on the result.
if scorm.objects.filter(Header__id=qp.id).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 as a normal QuerySet query.
从Django 1.2开始,您可以使用
exists()
:https://docs.djangoproject.com/en/dev/ref/models/querysets/#exists
使用^{} :
与
len()
相比,QuerySet的优势在于,它还没有被评估:考虑到这一点,When QuerySets are evaluated值得一读。
如果使用
get()
,例如scorm.objects.get(pk=someid)
,并且对象不存在,则会引发ObjectDoesNotExist
异常:更新: 也可以使用^{} :
相关问题 更多 >
编程相关推荐