Django检查是否存在查询 [英] Django check for any exists for a query

查看:98
本文介绍了Django检查是否存在查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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 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.

请记住, 对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, 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检查是否存在查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆