Django教程-02连接初始化数据库

Django教程-02连接初始化数据库,第1张

Django教程——01安装使用

在上面一篇文章里,介绍了安装Django的方法,这里说说连接数据库

这篇主要介绍踩的坑和解决办法

正常连接和初始化数据库的命令是

执行这个命令的时候,出现了如下报错

经过一段排查,是我配置数据库的时候,多嵌套了一层default,修改为如下即可

然后继续执行migrate时,会报如下错误

本机环境是mac电脑,按官方教程 *** 作的时候,发现安装mysqlclient的python包会依赖本机安装mysql或者mysql-client,但在装mysql和mysql-client的时候,发现一直报错。后面发现解决办法是,在settingspy文件里,加下如下代码,即改用pymsql连接即可。

或者在settingspy同目录的__init__py里加如上代码也可以

然后再执行python managepy migrate命令会发现表顺利创建。新增表,不影响原有库的其他表。

1 创建项目

运行下面命令就可以创建一个 django 项目,项目名称叫 mysite :

$ django-adminpy startproject mysite

创建后的项目目录如下:

mysite

├── managepy

└── mysite

├── __init__py

├── settingspy

├── urlspy

└── wsgipy

1 directory, 5 files

说明:

__init__py :让 Python 把该目录当成一个开发包 (即一组模块)所需的文件。 这是一个空文件,一般你不需要修改它。

managepy :一种命令行工具,允许你以多种方式与该 Django 项目进行交互。 键入python managepy help,看一下它能做什么。 你应当不需要编辑这个文件;在这个目录下生成它纯是为了方便。

settingspy :该 Django 项目的设置或配置。

urlspy:Django项目的URL路由设置。目前,它是空的。

wsgipy:WSGI web 应用服务器的配置文件。更多细节,查看 How to deploy with WSGI

接下来,你可以修改 settingspy 文件,例如:修改 LANGUAGE_CODE、设置时区 TIME_ZONE

SITE_ID = 1

LANGUAGE_CODE = 'zh_CN'

TIME_ZONE = 'Asia/Shanghai'

USE_TZ = True

上面开启了 [Time zone]() 特性,需要安装 pytz:

$ sudo pip install pytz

2 运行项目

在运行项目之前,我们需要创建数据库和表结构,这里我使用的默认数据库:

$ python managepy migrate

Operations to perform:

Apply all migrations: admin, contenttypes, auth, sessions

Running migrations:

Applying contenttypes0001_initial OK

Applying auth0001_initial OK

Applying admin0001_initial OK

Applying sessions0001_initial OK

然后启动服务:

$ python managepy runserver

你会看到下面的输出:

Performing system checks

System check identified no issues (0 silenced)

January 28, 2015 - 02:08:33

Django version 171, using settings 'mysitesettings'

Starting development server at

Quit the server with CONTROL-C

这将会在端口8000启动一个本地服务器, 并且只能从你的这台电脑连接和访问。 既然服务器已经运行起来了,现在用网页浏览器访问 。你应该可以看到一个令人赏心悦目的淡蓝色 Django 欢迎页面它开始工作了。

你也可以指定启动端口:

$ python managepy runserver 8080

以及指定 ip:

$ python managepy runserver 0000:8000

3 创建 app

前面创建了一个项目并且成功运行,现在来创建一个 app,一个 app 相当于项目的一个子模块。

在项目目录下创建一个 app:

$ python managepy startapp polls

如果 *** 作成功,你会在 mysite 文件夹下看到已经多了一个叫 polls 的文件夹,目录结构如下:

polls

├── __init__py

├── adminpy

├── migrations

│ └── __init__py

├── modelspy

├── testspy

└── viewspy

1 directory, 6 files

4 创建模型

每一个 Django Model 都继承自 djangodbmodelsModel

在 Model 当中每一个属性 attribute 都代表一个 database field

通过 Django Model API 可以执行数据库的增删改查, 而不需要写一些数据库的查询语句

打开 polls 文件夹下的 modelspy 文件。创建两个模型:

import datetime

from djangodb import models

from djangoutils import timezone

class Question(modelsModel):

question_text = modelsCharField(max_length=200)

pub_date = modelsDateTimeField('date published')

def was_published_recently(self):

return selfpub_date >= timezonenow() - datetimetimedelta(days=1)

class Choice(modelsModel):

question = modelsForeignKey(Question)

choice_text = modelsCharField(max_length=200)

votes = modelsIntegerField(default=0)

然后在 mysite/settingspy 中修改 INSTALLED_APPS 添加 polls:

INSTALLED_APPS = (

'djangocontribadmin',

'djangocontribauth',

'djangocontribcontenttypes',

'djangocontribsessions',

'djangocontribmessages',

'djangocontribstaticfiles',

'polls',

)

在添加了新的 app 之后,我们需要运行下面命令告诉 Django 你的模型做了改变,需要迁移数据库:

$ python managepy makemigrations polls

你会看到下面的输出日志:

Migrations for 'polls':

0001_initialpy:

- Create model Choice

- Create model Question

- Add field question to choice

你可以从 polls/migrations/0001_initialpy 查看迁移语句。

运行下面语句,你可以查看迁移的 sql 语句:

$ python managepy sqlmigrate polls 0001

输出结果:

BEGIN;

CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);

CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);

CREATE TABLE "polls_choice__new" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "polls_question" ("id"));

INSERT INTO "polls_choice__new" ("choice_text", "votes", "id") SELECT "choice_text", "votes", "id" FROM "polls_choice";

DROP TABLE "polls_choice";

ALTER TABLE "polls_choice__new" RENAME TO "polls_choice";

CREATE INDEX polls_choice_7aa0f6ee ON "polls_choice" ("question_id");

COMMIT;

你可以运行下面命令,来检查数据库是否有问题:

$ python managepy check

再次运行下面的命令,来创建新添加的模型:

$ python managepy migrate

Operations to perform:

Apply all migrations: admin, contenttypes, polls, auth, sessions

Running migrations:

Applying polls0001_initial OK

总结一下,当修改一个模型时,需要做以下几个步骤:

修改 modelspy 文件

运行 python managepy makemigrations 创建迁移语句

运行 python managepy migrate,将模型的改变迁移到数据库中

你可以阅读 django-adminpy documentation,查看更多 managepy 的用法。

创建了模型之后,我们可以通过 Django 提供的 API 来做测试。运行下面命令可以进入到 python shell 的交互模式:

$ python managepy shell

下面是一些测试:

>>> from pollsmodels import Question, Choice # Import the model classes we just wrote

# No questions are in the system yet

>>> Questionobjectsall()

[]

# Create a new Question

# Support for time zones is enabled in the default settings file, so

# Django expects a datetime with tzinfo for pub_date Use timezonenow()

# instead of datetimedatetimenow() and it will do the right thing

>>> from djangoutils import timezone

>>> q = Question(question_text="What's new", pub_date=timezonenow())

# Save the object into the database You have to call save() explicitly

>>> qsave()

# Now it has an ID Note that this might say "1L" instead of "1", depending

# on which database you're using That's no biggie; it just means your

# database backend prefers to return integers as Python long integer

# objects

>>> qid

1

# Access model field values via Python attributes

>>> qquestion_text

"What's new"

>>> qpub_date

datetimedatetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)

# Change values by changing the attributes, then calling save()

>>> qquestion_text = "What's up"

>>> qsave()

# objectsall() displays all the questions in the database

>>> Questionobjectsall()

[<Question: Question object>]

打印所有的 Question 时,输出的结果是 [<Question: Question object>],我们可以修改模型类,使其输出更为易懂的描述。修改模型类:

from djangodb import models

class Question(modelsModel):

#

def __str__(self): # __unicode__ on Python 2

return selfquestion_text

class Choice(modelsModel):

#

def __str__(self): # __unicode__ on Python 2

return selfchoice_text

接下来继续测试:

>>> from pollsmodels import Question, Choice

# Make sure our __str__() addition worked

>>> Questionobjectsall()

[<Question: What's up>]

# Django provides a rich database lookup API that's entirely driven by

# keyword arguments

>>> Questionobjectsfilter(id=1)

[<Question: What's up>]

>>> Questionobjectsfilter(question_text__startswith='What')

[<Question: What's up>]

# Get the question that was published this year

>>> from djangoutils import timezone

>>> current_year = timezonenow()year

>>> Questionobjectsget(pub_date__year=current_year)

<Question: What's up>

# Request an ID that doesn't exist, this will raise an exception

>>> Questionobjectsget(id=2)

Traceback (most recent call last):

DoesNotExist: Question matching query does not exist

# Lookup by a primary key is the most common case, so Django provides a

# shortcut for primary-key exact lookups

# The following is identical to Questionobjectsget(id=1)

>>> Questionobjectsget(pk=1)

<Question: What's up>

# Make sure our custom method worked

>>> q = Questionobjectsget(pk=1)

# Give the Question a couple of Choices The create call constructs a new

# Choice object, does the INSERT statement, adds the choice to the set

# of available choices and returns the new Choice object Django creates

# a set to hold the "other side" of a ForeignKey relation

# (eg a question's choice) which can be accessed via the API

>>> q = Questionobjectsget(pk=1)

# Display any choices from the related object set -- none so far

>>> qchoice_setall()

[]

# Create three choices

>>> qchoice_setcreate(choice_text='Not much', votes=0)

<Choice: Not much>

>>> qchoice_setcreate(choice_text='The sky', votes=0)

<Choice: The sky>

>>> c = qchoice_setcreate(choice_text='Just hacking again', votes=0)

# Choice objects have API access to their related Question objects

>>> cquestion

<Question: What's up>

# And vice versa: Question objects get access to Choice objects

>>> qchoice_setall()

[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]

>>> qchoice_setcount()

3

# The API automatically follows relationships as far as you need

# Use double underscores to separate relationships

# This works as many levels deep as you want; there's no limit

# Find all Choices for any question whose pub_date is in this year

# (reusing the 'current_year' variable we created above)

>>> Choiceobjectsfilter(question__pub_date__year=current_year)

[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]

# Let's delete one of the choices Use delete() for that

>>> c = qchoice_setfilter(choice_text__startswith='Just hacking')

>>> cdelete()

>>>

上面这部分测试,涉及到 django orm 相关的知识,详细说明可以参考 Django中的ORM。

5 管理 admin

Django有一个优秀的特性, 内置了Django admin后台管理界面, 方便管理者进行添加和删除网站的内容

新建的项目系统已经为我们设置好了后台管理功能,见 mysite/settingspy:

INSTALLED_APPS = (

'djangocontribadmin', #默认添加后台管理功能

'djangocontribauth',

'djangocontribcontenttypes',

'djangocontribsessions',

'djangocontribmessages',

'djangocontribstaticfiles',

'mysite',

)

同时也已经添加了进入后台管理的 url, 可以在 mysite/urlspy 中查看:

url(r'^admin/', include(adminsiteurls)), #可以使用设置好的url进入网站后台

接下来我们需要创建一个管理用户来登录 admin 后台管理界面:

$ python managepy createsuperuser

Username (leave blank to use 'june'): admin

Email address:

Password:

Password (again):

Superuser created successfully

总结

最后,来看项目目录结构:

mysite

├── dbsqlite3

├── managepy

├── mysite

│ ├── __init__py

│ ├── settingspy

│ ├── urlspy

│ ├── wsgipy

├── polls

│ ├── __init__py

│ ├── adminpy

│ ├── migrations

│ │ ├── 0001_initialpy

│ │ ├── __init__py

│ ├── modelspy

│ ├── templates

│ │ └── polls

│ │ ├── detailhtml

│ │ ├── indexhtml

│ │ └── resultshtml

│ ├── testspy

│ ├── urlspy

│ ├── viewspy

└── templates

└── admin

└── base_sitehtm

通过上面的介绍,对 django 的安装、运行以及如何创建视 图和模型有了一个清晰的认识,接下来就可以深入的学习 django 的自动化测试、持久化、中间件、国 际 化等知识。

在django程序外部使用djangomodels,我给你端示例代码你看看:

fromdjangocoremanagementimportsetup_environ

importQBsettings

setup_environ(QBsettings)

fromrechargemodelsimportOrder,QB是我的project名称,recharge是我的app名称

首先你打开localhost的提示是正常,说明你搭建django是成功了,只是你没有创建任何app,或者你创建了app但是没有同步到数据库(python managepy makemigratons,python managepy migrate,这两个命令必须在django17以上版本),如果你还没有任何app也可以执行,会创建内置的用户系统,等等。可以到localhost:8000/admin查看是否创建成功。

初始化数据库时会咨询你是否创建超级用户(即管理员)

然后python managepy migrate并不是在python文件目录执行,而是到你创建django项目中执行,找到managepy 这个文件的路径

以上就是关于Django教程-02连接初始化数据库全部的内容,包括:Django教程-02连接初始化数据库、django项目 makemigrations时出现django.db.migrations.graph.nodenotfounderror错误。、django数据库使用(django *** 作mysql数据库)等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/9765896.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-01
下一篇 2023-05-01

发表评论

登录后才能评论

评论列表(0条)

保存