blog icon indicating copy to clipboard operation
blog copied to clipboard

Django filter→QuerySet get→Object

Open qingquan-li opened this issue 4 years ago • 0 comments

一、QuerySet中可以包含多个Object

参考:https://docs.djangoproject.com/zh-hans/3.1/topics/db/queries/#retrieving-objects

一个 QuerySet 代表来自数据库中对象的一个集合。它可以有 0 个,1 个或者多个 filters 。 Filters 可以根据给定参数缩小查询结果量。在 SQL 的层面上,QuerySet 对应 SELECT 语句,而 filters 对应类似 WHERELIMIT 的限制子句。


二、对比get,filter返回空值不报错

参考:https://stackoverflow.com/questions/42899919/django-queryset-and-filter-vs-get

The difference is that filter returns a queryset object, wheras get returns the required object.

If you use filter(), you typically do this whenever you expect more than just one object that matches your criteria. If no item was found matching your criteria, filter() returns am empty queryset without throwing an error.

If you use get(), you expect one (and only one) item that matches your criteria. Get throws an error if the item does not exist or if multiple items exist that match your criteria. You should therefore always use if in a try.. except .. block


三、实例

  • model_name.objects.get(pk=1) 返回 Object
  • model_name.objects.filter(pk=1) 返回 QuerySet
  • model_name.objects.filter(pk=1).first() 返回 Object

qingquan-li avatar Jan 29 '21 18:01 qingquan-li