从 Django 中的查询集中获取第一个对象的最快方法? [英] Fastest way to get the first object from a queryset in django?
问题描述
我经常发现自己想要从 Django 的查询集中获取第一个对象,或者如果没有则返回 None
.有很多方法可以做到这一点,这些方法都有效.但我想知道哪个性能最好.
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
另一种选择是:
qs = MyModel.objects.filter(blah = blah)
try:
return qs[0]
except IndexError:
return None
这会生成单个数据库调用,这很好.但是很多时候需要创建一个异常对象,当你真正需要的只是一个微不足道的 if 测试时,这是一个非常占用内存的事情.
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?
推荐答案
Use the convenience methods .first()
and .last()
:
MyModel.objects.filter(blah=blah).first()
如果查询集没有返回任何对象,它们都会吞下结果异常并返回None
.
They both swallow the resulting exception and return None
if the queryset returns no objects.
这些是在 Django 1.6 中添加的,它是 发布于2013 年 11 月.
These were added in Django 1.6, which was released in Nov 2013.
这篇关于从 Django 中的查询集中获取第一个对象的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!