在django中从queryset获取第一个对象的最快方法? [英] Fastest way to get the first object from a queryset in django?

查看:215
本文介绍了在django中从queryset获取第一个对象的最快方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常我发现自己想要从Django中的查询集中获取第一个对象,如果没有,返回 None 。有很多方法可以做到这一切都有效。但是我想知道哪个是最优秀的。

  qs = MyModel.objects.filter(blah = blah)
如果qs.count()> 0:
return qs [0]
else:
return无

这是否导致两个数据库调用?这似乎很浪费。这更快吗?

  qs = MyModel.objects.filter(blah = blah)
如果len(qs)> 0:
return qs [0]
else:
return无

另一个选择是:

  qs = MyModel.objects.filter(blah = blah)
try:
return qs [0]
除了IndexError:
return无

这产生一个单一的数据库调用,这是很好的。但是需要很多时候创建一个异常对象,这是一个非常内存密集的事情,当你真正需要的是一个微不足道的if-test。



我可以通过一个单一的数据库调用来执行此操作,而不会使用异常对象来调用内存?

解决方案

Django 1.6(2013年11月发布)介绍了方便方法 first() last() code>如果查询器没有返回任何对象,则会吞入结果异常并返回


Often I find myself wanting to get the first object from a queryset in Django, or return None if there aren't any. There are lots of ways to do this which all work. But I'm wondering which is the most performant.

qs = MyModel.objects.filter(blah = blah)
if qs.count() > 0:
    return qs[0]
else:
    return None

Does this result in two database calls? That seems wasteful. Is this any faster?

qs = MyModel.objects.filter(blah = blah)
if len(qs) > 0:
    return qs[0]
else:
    return None

Another option would be:

qs = MyModel.objects.filter(blah = blah)
try:
    return qs[0]
except IndexError:
    return None

This generates a single database call, which is good. But requires creating an exception object a lot of the time, which is a very memory-intensive thing to do when all you really need is a trivial if-test.

How can I do this with just a single database call and without churning memory with exception objects?

解决方案

Django 1.6 (released Nov 2013) introduced the convenience methods first() and last() which swallow the resulting exception and return None if the queryset returns no objects.

这篇关于在django中从queryset获取第一个对象的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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