在 Windows Terminal 中激活 virtual environment 的方法:
On Windows, the equivalent activate script is in the Scripts folder:
\path\to\env\Scripts\activate
修改setting.py中的配置:
TIME_ZONE = ‘Asia/Shanghai’
LANGUAGE_CODE = ‘zh-cn’
结果运行项目时报错了,如下:
django IOError: No translation files found for default language zh-cn
把 'zh-cn'
更改为 'zh-hans'
问题解决。
在 view 中写好视图
在 urls 中写好路由匹配
在 setting 中的 INSTALLED_APPS 中加入应用的配置路径
在 models 中定义好数据模型,然后执行
python manage.py makemigrations charts
执行结果为
Migrations for 'charts':
charts\migrations\0001_initial.py
- Create model InvoiceModel
代表对charts应用中的数据模型所做的修改(这里是创建了一个新的model)已经被执行并作为migrations存储起来。
执行
python manage.py migrate
发生了一个错误:
django.db.utils.OperationalError: table “charts_invoicemodel” has
more than one primary key
Django 中不允许多重 Primary Key,但可以使用默认的ID作为Key,然后加上一个约束来模拟多重PK,具体如下:
class MyModel(models.Model):
col1 = models.CharField()
col2 = models.CharField()
class Meta:
unique_together = (("col1", "col2"),)
然后重新运行
python manage.py makemigrations charts
发现还是会报相同的错误,遂删掉上一次执行该命令生成的0001.initial.py 文件,然后重新执行makemigrations 命令,成功。
如果想看看 migrations 到底执行了哪些SQL语句,可以运行如下命令:
python manage.py sqlmigrate charts 0001
sqlmigrate 命令接受两个参数,应用名和迁移名,返回对应的迁移执行的SQL语句:
BEGIN;
--
--Rename model InvoiceModel to Invoice
--
ALTER TABLE "charts_invoicemodel" RENAME TO "charts_invoice";
COMMIT;
我使用的是SQLite3数据库,具体的返回结果会随数据库的选择不通过而返回不同的结果。
sqlmigrate 命令不会真的执行返回的SQL语句,若要将迁移应用到数据库中使所做的改动生效,需要再次执行:
python manage.py migrate
返回如下结果:
Operations to perform:
Apply all migrations: admin, auth, charts, contenttypes, sessions
Running migrations:
Applying charts.0002_auto_20170712_1108... OK
migrate 命令接受所有未应用的迁移。
最后总结数据模型更改的三步指南:
- 更改模型(models.py中)
- 运行
python manage.py makemigrations <appname>
创建模型变更的迁移 - 运行
python manage.py migrate
将全部迁移应用到数据库
Over!
Playing with the API
python manage.py shell
进入Shell 后就可以调用Django提供的各种API,比如:
>>> from charts.models import Invoice
>>> Invoice.objects.all()
<QuerySet [<Invoice: Invoice object>]>
>>> Invoice.objects.filter(id=1)
<QuerySet [<Invoice: Invoice object>]>
>>> Invoice.objects.filter(linkedAccountId__startswith='132')
<QuerySet [<Invoice: Invoice object>]>
Django Admin
创建管理员账户:
python manage.py createsuperuser
然后使用该账户登陆该URL:
127.0.0.1:8000/admin
进入管理页面后并没有发现自己创建的app, 回到创建的app路径下打开 admin.py 文件,导入该app中添加的models并注册该models。
# charts/admin.py
from .models import Invoice
admin.site.register(Invoice)
重启服务,这时可以在Admin管理页面看到新创建的app以及其中的Model。