对于简单的SQL语句,我们还是可以直接使用Django自带的ORM框架,来简化代码的。那么对于查询语句,get()和filter()的区别让我在项目里吃了不少苦头,经常遇到bug,不知不觉就指向了这两个问题,所以今天我准备好好的总结一下相关区别。
我就结合Django官方文档中给出的定义和我自己的一些理解进行介绍:
get()
- 不使用缓存
These methods do not use a cache (see Caching and QuerySets). Rather, they query the database each time they’re called.
- 返回的是object对象
- 传入的参数需要是唯一的(例如,主键),可以传入字典的形式
Returns the object matching the given lookup parameters, which should be in the format described in Field lookups. You should use lookups that are guaranteed unique, such as the primary key or fields in a unique constraint.
- 如果get()无法找到任何对象,就会报Model.DoesNotExist 异常
- 如果g