运维工程师的进阶之路

2019-06-13 Django连接mysql

2019-06-13  本文已影响0人  Gswu

1 配置mysql连接

setting.py 配置:


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django-test',
        'USER': 'root',
        'PASSWORD': 'password',
        'HOST': '192.168.37.134',
        'PORT':'3306'
    }
}

两种操作方式:mysql语句(python db api)或ORM模型

排错:

2 编写app下的models配置文件。我们使用的例子是新建一个book app:

命令行下: python manage.py startapp book

编辑models配置文件如下

from django.db import models

# Create your models here.

#创建一个模型(类),对应数据库中的一张表
#一个普通类要映射到数据库,需要指定父类models.Model
class Book(models.Model):
    #模型中的一个属性,对应数据库中的一张表
    id=models.AutoField(primary_key=True)
    name=models.CharField(max_length=100,null=False)
    author=models.CharField(max_length=100,null=False)
    price=models.FloatField(null=False,default=0)

# 一个模型的对象,对应数据库中的一条数据
# book=Book(name="三国演义",author="罗贯中",price=99.99)
#save 方法,相当于保存到数据库
# book.save()
#delete 方法,相当于是从数据库中删除
# book.delete()

3 增加setting配置 installed app

增加 ‘book’

4 生成迁移脚本文件

会每次坚持改动,生成增量改变的脚本

(venv) E:\DjangoPro\untitled>python manage.py makemigrations

Migrations for 'book':
  book\migrations\0001_initial.py
    - Create model Book


5 使用 migrate将新生成的迁移脚本文件映射到数据库中

python manage.py migrate

报错:

django.db.utils.InternalError: (1665, 'Cannot execute statement: impossible to write to binary log since BINLOG_FORMAT = STATEMENT and at least one table uses a st

orage engine limited to row-based logging. InnoDB is limited to row-logging when transaction isolation level is READ COMMITTED or READ UNCOMMITTED.')

处理:

在数据库的/etc/my.cnf 中添加以下配置:

binlog_format=mixed

清空数据库后再操作就成功了

(venv) E:\DjangoPro\untitled>python manage.py migrate

Operations to perform:

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

Running migrations:

Applying contenttypes.0001_initial... OK

Applying auth.0001_initial... OK

Applying admin.0001_initial... OK

Applying admin.0002_logentry_remove_auto_add... OK

Applying admin.0003_logentry_add_action_flag_choices... OK

Applying contenttypes.0002_remove_content_type_name... OK

Applying auth.0002_alter_permission_name_max_length... OK

Applying auth.0003_alter_user_email_max_length... OK

Applying auth.0004_alter_user_username_opts... OK

Applying auth.0005_alter_user_last_login_null... OK

Applying auth.0006_require_contenttypes_0002... OK

Applying auth.0007_alter_validators_add_error_messages... OK

Applying auth.0008_alter_user_username_max_length... OK

Applying auth.0009_alter_user_last_name_max_length... OK

Applying auth.0010_alter_group_name_max_length... OK

Applying auth.0011_update_proxy_permissions... OK

Applying book.0001_initial... OK

Applying sessions.0001_initial... OK

(venv) E:\DjangoPro\untitled>

以后每次增加数据库models,都需要:

python manage.py makemigrations 
python manage.py migrate
上一篇下一篇

猜你喜欢

热点阅读