- orm的定义
- 为什么要有orm
- orm的核心在哪
- 什么时候queryset 被 evaluated (个人理解为利用)
- 什么时候queryset会被缓存
- 什么时候缓存被破坏
- F查询和Q查询
- 多表查询会出现什么问题以及如何避免
- orm 是object-related-mapping 的缩写,翻译为对象关系映射------>将我们对编写的model模型操作 和对数据库里面的表字段的操作 相关联----->形成一种映射的关系
- 第二个问题放到后面作 核心在于懒加载(个人认为哈) 那么什么是懒加载:the act of creating a
- doesn’t involve any database activity.(当我们创建queryset时,并没有查询数据库)
- instances = Model.objects.all()------>并没有连接数据库,没对数据库中的表做任何操作(好处就是显而易见的数据库的负荷减少了)
- 文档说明:Internally, a
QuerySet
can be constructed, filtered, sliced, and generally passed around without actually hitting the database----->当queryset被创建,过滤,切片,传递的时候都没有真正的查询数据库
QuerySet
is evaluated – and, hence, a database query happens – Django saves the query results in the QuerySet
’s cache and returns the results that have been explicitly requested (e.g., the next element, if the QuerySet
is being iterated over)):
#错误示范
>>> print([e.headline for e in Entry.objects.all()])
>>> print([e.pub_date for e in Entry.objects.all()])
#这样就会进行两次迭代 两次hitting database#正确演绎
>>> queryset = Entry.objects.all()
>>> print([p.headline for p in queryset]) # Evaluate the query set.
>>> print([p.pub_date for p in queryset]) # Re-use the cache from the evaluation.
>>> queryset = Entry.objects.all()
>>> print(queryset[5]) # Queries the database
>>> print(queryset[5]) # Queries the database again
>>> queryset = Entry.objects.all()
>>> [entry for entry in queryset] # Queries the database
>>> print(queryset[5]) # Uses cache
>>> print(queryset[5]) # Uses cache
>>> [entry for entry in queryset]
>>> bool(queryset)
>>> entry in queryset
>>> list(queryset)