检查查询是否存在

2024-06-11 21:09:47 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

在php中就是这样做的

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

Tags: djangoidifobjectsmysql条目filtercondition
2条回答

从Django 1.2开始,您可以使用exists()

https://docs.djangoproject.com/en/dev/ref/models/querysets/#exists

if some_queryset.filter(pk=entity_id).exists():
    print("Entry contained in queryset")

使用^{}

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.

考虑到这一点,When QuerySets are evaluated值得一读。


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

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():
    ....

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.

相关问题 更多 >