exists的作用是反馈查询结果集是否为空,速度快。


exists()
exists()

Returns True if the QuerySet contains any results, and Falseif not. This tries to perform the query in the simplest and fastest waypossible, but it does execute nearly the same query as a normalQuerySet query.

exists() is useful for searches relating to bothobject membership in a QuerySet and to the existence of any objects ina QuerySet, particularly in the context of a large QuerySet.

The most efficient method of finding whether a model with a unique field(e.g. primary_key) is a member of a QuerySet is:

entry = Entry.objects.get(pk=123)
if some_queryset.filter(pk=entry.pk).exists():
    print("Entry contained in queryset")

Which will be faster than the following which requires evaluating and iteratingthrough the entire queryset:

if entry in some_queryset:
   print("Entry contained in QuerySet")

And to find whether a queryset contains any items:

if some_queryset.exists():
    print("There is at least one object in some_queryset")

Which will be faster than:

if some_queryset:
    print("There is at least one object in some_queryset")

… but not by a large degree (hence needing a large queryset for efficiencygains).

Additionally, if a some_queryset has not yet been evaluated, but you knowthat it will be at some point, then using some_queryset.exists() will domore overall work (one query for the existence check plus an extra one to laterretrieve the results) than simply using bool(some_queryset), whichretrieves the results and then checks if any were returned.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值