Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Django filter→QuerySet get→Object #161

Open
Qingquan-Li opened this issue Jan 29, 2021 · 0 comments
Open

Django filter→QuerySet get→Object #161

Qingquan-Li opened this issue Jan 29, 2021 · 0 comments
Labels

Comments

@Qingquan-Li
Copy link
Owner

一、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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant