Django orm get filter 查询数据库的时机

官方文档参考:

  https://docs.djangoproject.com/en/2.2/topics/db/optimization/

  https://docs.djangoproject.com/en/2.2/ref/models/querysets/#when-querysets-are-evaluated

get 方法:

Returns the object matching the given lookup parameters, which should be in the format described in Field lookups.

get() raises MultipleObjectsReturned if more than one object was found. The MultipleObjectsReturned exception is an attribute of the model class.

get() raises a DoesNotExist exception if an object wasn’t found for the given parameters. This exception is also an attribute of the model class

# 使用 get 方法时,会直接查询数据库,如果从数据库查询到一个匹配的结果,返回一个对象,如果没有记录或者匹配结果多于两个则会抛出异常
# 将缓存不可调用的属性(普通的模型字段),使用可调用属性每次都会导致DB查找(如外键字段)
# 以下为官方文档代码及注释:
  >>> entry = Entry.objects.get(id=1)
  >>> entry.blog   # Blog object is retrieved at this point
  >>> entry.blog   # cached version, no DB access
  
  
>>> entry = Entry.objects.get(id=1)   >>> entry.authors.all() # query performed   >>> entry.authors.all() # query performed again

# 该方法已经返回了所有字段数据,并进行了缓存,示例:
  >>> user = User.objects.first()
  >>> user.__dict__ # 一般的类对象或者实例对象都有 __dict__ 属性,用以查看对象内部所有属性名和属性值组成的字典,但也有例外,如数据类型对象 list dict 就没有(本身就是数据容器)
  可以看到该对象的内存位置及所有的模型字段数据:
    {'_state': <django.db.models.base.ModelState object at 0x7ff34b61ab00>, 'id': 1, 'password': ...}

filter 方法:

Returns a new QuerySet containing objects that do not match the given lookup parameters.

The lookup parameters (**kwargs) should be in the format described in Field lookups below. Multiple parameters are joined via AND in the underlying SQL statement, and the whole thing is enclosed in a NOT().

# query_set是惰性获取的,创建 query_set 的操作,不会进行任何数据库查询,我们可以多次的将筛选器堆叠在一起,Django在计算 query_set 之前不会实际运行查询,只有当 query_set 被使用到时才会查询数据库,
# 如遍历或者判断该 query_set 是否为 None 的时候(遍历 query_set, 会返回模型对象)。
# 当使用 filter 时,可以适当得使用 values() values_list() 方法,只获取自己需要的字段数据(模型对象是没有values() 与 values_list() 方法的)

使用 orm 肯定没有使用原生的 sql 语句好,但是 django 还是提供了很多的 orm 方法去提高查询性能

https://docs.djangoproject.com/en/2.2/ref/models/querysets/#when-querysets-are-evaluated

https://docs.djangoproject.com/en/2.2/topics/db/optimization/

原文地址:https://www.cnblogs.com/lowmanisbusy/p/12487824.html