Fastest way to get the first object from a queryset in django?
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(2013年11月发布)引入了便利方法first()
和last()
,该方法吞下产生的异常,如果queryset不返回对象,则返回None
。
The correct answer is
Entry.objects.all()[:1].get()
Which can be used in:
Entry.objects.filter()[:1].get()
You wouldn't want to first turn it into a list because that would force a full database call of all the records. Just do the above and it will only pull the first. You could even use .order_by
to ensure you get the first you want.
Be sure to add the .get()
or else you will get a QuerySet back and not an object.
r = list(qs[:1])
if r:
return r[0]
return None
链接地址: http://www.djcxy.com/p/38714.html
上一篇: 带有值列表的Django过滤器