You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
The text was updated successfully, but these errors were encountered:
一、QuerySet中可以包含多个Object
参考:https://docs.djangoproject.com/zh-hans/3.1/topics/db/queries/#retrieving-objects
二、对比get,filter返回空值不报错
参考:https://stackoverflow.com/questions/42899919/django-queryset-and-filter-vs-get
三、实例
model_name.objects.get(pk=1)
返回 Objectmodel_name.objects.filter(pk=1)
返回 QuerySetmodel_name.objects.filter(pk=1).first()
返回 ObjectThe text was updated successfully, but these errors were encountered: