在django中从queryset获取第一个对象的最快方法? [英] Fastest way to get the first object from a queryset in 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屋!