Index for DB: https://docs.djangoproject.com/en/2.2/topics/db/
QuerySet API reference:https://docs.djangoproject.com/en/1.11/ref/models/querysets/
Performance and optimization - https://docs.djangoproject.com/en/1.11/topics/performance/
...你可以使用 python manage.py shell
来让 ORM 执行查询以玩耍:
$ python manage.py shell
>>> from core import models
>>> a = models.User.objects[0:5]
...
如果你使用 MySQL,还可以结合General Log来实时查看 MySQL的 SQL 执行日志以进行验证(Visit 【MySQL】日志记录 for more details)。
意思就是说要在对应的 level (M V C) 做对应的事。e.g. 如果计算 court, 在最低的数据库 level 里是最快的(如果只需要知道此记录是否存在的话,用 exists()
会更快)。
但要 注意
: queryset 是 lazy 的,所以有时候在 higher level (例如模板)里控制 queryset 是否真的执行,说不定会更高效。
下面这段代码很好的解释了不同 level 的意思:
# QuerySet operation on the database
# fast, because that's what databases are good at
my_bicycles.count()
# counting Python objects
# slower, because it requires a database query anyway, and processing
# of the Python objects
len(my_bicycles)
# Django template filter
# slower still, because it will have to count them in Python anyway,
# and because of template language overheads
\{\{ my_bicycles|length \}\}
当通过 Model 声明完表结构后,Django 可以自动将 Model 声明转换成DB Schema,进而自动写入 DB 中。
在>=1.7 的 Django 中,可以使用以下方法来生成 DB schema:
$ python manage.py makemigrations
$ python manage.py migrate
The makemigrations
command looks at all your available models and creates migrations for whichever tables don’t already exist. migrate
runs the migrations and creates tables in your database, as well as optionally providing much richer schema control.
在 1.7 之前的版本,使用:
$ python manage.py syncdb