Fastest way to get the first object from a queryset in django?

前端 未结 8 1135
有刺的猬
有刺的猬 2020-12-12 09:17

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

8条回答
  •  萌比男神i
    2020-12-12 09:57

    You can use array slicing:

    Entry.objects.all()[:1].get()
    

    Which can be used with .filter():

    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.

提交回复
热议问题