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

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

问题描述

在django中如何检查查询是否存在任何条目

sc=scorm.objects.filter(Header__id=qp.id)

这是在php中完成的方式

if(mysql_num_rows($resultn)) {//真条件}别的 {//错误条件}

解决方案

您可以使用 exists():

if scorm.objects.filter(Header__id=qp.id).exists():....

<块引用>

如果 QuerySet 包含任何结果,则返回 True,否则返回 False.这会尝试以最简单和最快的方式执行查询,但它执行的查询与普通 QuerySet 查询几乎相同.

旧版本: (<1.2)

使用count():

sc=scorm.objects.filter(Header__id=qp.id)如果 sc.count() >0:...

优于例如len() 是,QuerySet 尚未评估:

<块引用>

count() 在幕后执行 SELECT COUNT(*),所以你应该总是使用 count() 而不是加载所有将记录转换为 Python 对象并在结果上调用 len().

考虑到这一点,何时评估 QuerySet 值得一读.


如果您使用 get(),例如scorm.objects.get(pk=someid),并且对象不存在,引发ObjectDoesNotExist异常:

from django.core.exceptions import ObjectDoesNotExist尝试:sc = scorm.objects.get(pk=someid)除了 ObjectDoesNotExist:打印 ...

In django how to check whether any entry exists for a query

sc=scorm.objects.filter(Header__id=qp.id)

This was how it was done in php

if(mysql_num_rows($resultn)) {
    // True condition
    }
else {
    // False condition
    }

解决方案

You can use exists():

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.

Older versions: (<1.2)

Use count():

sc=scorm.objects.filter(Header__id=qp.id)

if sc.count() > 0:
   ...

The advantage over e.g. len() is, that the QuerySet is not yet evaluated:

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.

Having this in mind, When QuerySets are evaluated can be worth reading.


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

这篇关于Django 检查查询是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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