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

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

    It can be like this

    obj = model.objects.filter(id=emp_id)[0]
    

    or

    obj = model.objects.latest('id')
    

提交回复
热议问题