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

前端 未结 8 1155
有刺的猬
有刺的猬 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:46

    Now, in Django 1.9 you have first() method for querysets.

    YourModel.objects.all().first()
    

    This is a better way than .get() or [0] because it does not throw an exception if queryset is empty, Therafore, you don't need to check using exists()

提交回复
热议问题