DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
修改配置文件如下:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends. sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': ' C:\My Files\Python Projects\mysite\MyDB.db', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
完成设置并保存之后我们测试一下配置。 同样,在“mysite”项目目录下执行前面提到的“python manage.py shell”环境来进行测试。
输入下面的命令来测试数据库配置是否正确:
>>> from django.db import connection
>>> cursor = connection.cursor()
如果没有显示什么错误信息,那么数据库配置是正确的。
INSTALLED_APPS = (
#'django.contrib.auth',
#'django.contrib.contenttypes',
#'django.contrib.sessions',
#'django.contrib.sites',
#'django.contrib.messages',
#'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'inventory',
)
现在我们可以创建数据库表了。 首先,用下面的命令验证模型的有效性:
python manage.py validate
validate 命令检查你的模型的语法和逻辑是否正确。 如果一切正常,你会看到 0 errors found 消息。如果出错,根据错误信息来帮助你修正你的模型。
python manage.py sqlall inventory
执行之后,输出如下:
BEGIN;
CREATE TABLE "inventory_item" (
"ItemId" integer NOT NULL PRIMARY KEY,
"ItemCode" varchar(50) NOT NULL,
"ItemName" varchar(50) NOT NULL
);
CREATE TABLE "inventory_inventory" (
"InventoryId" integer NOT NULL PRIMARY KEY,
"Item_id" integer NOT NULL REFERENCES "inventory_item" ("ItemId"),
"Amount" integer
);
CREATE TABLE "inventory_instockbill" (
"InStockBillId" integer NOT NULL PRIMARY KEY,
"InStockBillCode" varchar(40) NOT NULL,
"InStockDate" datetime,
"Operator" varchar(40) NOT NULL,
"Item_id" integer NOT NULL REFERENCES "inventory_item" ("ItemId"),
"Amount" integer
);
CREATE INDEX "inventory_inventory_70e6447b" ON "inventory_inventory" ("Item_id");
CREATE INDEX "inventory_instockbill_70e6447b" ON "inventory_instockbill" ("Item_id");
COMMIT;
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = False 5.4.4. 数据排序
在你的 Django 应用中,你或许希望根据某字段的值对检索结果排序,比如说,按字母顺序。 那么,使用 order_by() 这个方法就可以搞定了。