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

前端 未结 8 1140
有刺的猬
有刺的猬 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条回答
  •  情歌与酒
    2020-12-12 10:11

    Use the convenience methods .first() and .last():

    MyModel.objects.filter(blah=blah).first()
    

    They both swallow the resulting exception and return None if the queryset returns no objects.

    These were added in Django 1.6, which was released in Nov 2013.

提交回复
热议问题