Django入门开发之数据模型01
1. Django安装
[root@HappyLau ~]# pip install django==1.8.2
2. 创建项目
[root@HappyLau html]# django-admin startproject demo 查看项目的结构: [root@HappyLau html]# tree demo/ demo/ ├── demo │ ├── __init__.py │ ├── __init__.pyc │ ├── settings.py │ ├── settings.pyc │ ├── urls.py │ └── wsgi.py └── manage.py 1 directory, 7 files demo目录文件说明: __init__.py 代表是一个包 settings.py 配置文件,环境设定 urls.py urls地址映射关系 wsgi.py wsgi.py设定,django是遵循WSGI协议的框架
3. 配置数据库
Django默认采用sqllite3数据库作为数据持久存储,实际工作中一般使用MySQL作为结构化数据存储,在python2中使用python-MySQL作为python和MySQL数据库交互的API,而python3中使用pymysql,且不支持python-MySQL,所以以pymysql作为主体使用,需要在项目/应用的__init__.py文件中定义使用如下:
[root@HappyLau demo]# cat demo/__init__.py import pymysql pymysql.install_as_MySQLdb()
1. 安装MySQL数据库和pymysql模块
root@HappyLau demo]# yum install mariadb mariadb-server python2-PyMySQL -y
修改MariaDB的默认字符集,修改server端
[root@HappyLau demo]# vim /etc/my.cnf.d/server.cnf
[server]
character-set-server=utf8
# this is only for the mysqld standalone daemon
[mysqld]
character-set-server=utf8
修改client端:
[root@HappyLau demo]# vim /etc/my.cnf.d/client.cnf
[client]
default-character-set=utf8
启动数据库:
[root@HappyLau demo]# systemctl restart mariadb
[root@HappyLau demo]# systemctl enable mariadb
2. 数据库环境准备
MariaDB [(none)]> create database book; Query OK, 1 row affected (0.01 sec) MariaDB [(none)]> MariaDB [(none)]> grant all privileges on book.* to 'bookadmin'@'localhost' identified by 'bookpassword'; Query OK, 0 rows affected (0.04 sec) MariaDB [(none)]> flush privileges; Query OK, 0 rows affected (0.02 sec)
3. 配置Django数据库连接,修改settings.py文件,找到DATABASES行,修改内容如下:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': 'localhost', 'PORT': 3306, 'USER': 'bookadmin', 'PASSWORD': 'bookpassword', 'NAME': 'book' } }
4. 创建和管理应用
1. 创建应用
[root@HappyLau demo]# django-admin startapp book 查看应用目录结构: [root@HappyLau demo]# tree book/ book/ ├── admin.py ├── __init__.py ├── migrations │ └── __init__.py ├── models.py ├── tests.py └── views.py 1 directory, 6 files
2. 将应用注册到django中,修改项目的settings.py文件,找到INSTALLED_APPS行,将book应用添加到其中,如下:
INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'book' )
4. 编写应用模型
1. 定义模型的类,在每个应用包目录下的models.py文件中定义,如book应用的的book/models.py文件,定义两个模型:书本和英雄模型,其中书本作为英雄的外键而存在,如果有多个应用则在各自的应用中定义模型即可,定义如下:
[root@HappyLau demo]# cat book/models.py #_*_ coding:utf8 _*_ from django.db import models class Book(models.Model): ''' @models.Model,定义Book数据库models类 ''' book_name = models.CharField(max_length=128) author_name = models.CharField(max_length=128) publish_date = models.DateTimeField() def __str__(self): '''格式化输出''' return self.book_name,self.author_name,self.publish_date class Hero(models.Model): ''' @models.Model,定义超人Hero数据库models类 ''' hero_name = models.CharField(max_length=128) hero_sex = models.BooleanField() hero_content = models.CharField(max_length=1024) hero_book = models.ForeignKey(Book) def __str__(self): '''格式化输出''' return self.hero_name,self.hero_sex,self.hero_content,self.hero_book
2. 生成模型所需的表
[root@HappyLau demo]# python manage.py makemigrations Migrations for 'book': 0001_initial.py: - Create model Book - Create model Hero
[root@HappyLau demo]# python manage.py migrate
Operations to perform:
Synchronize unmigrated apps: staticfiles, messages
Apply all migrations: admin, contenttypes, book, auth, sessions
Synchronizing apps without migrations:
Creating tables...
Running deferred SQL...
Installing custom SQL...
Running migrations:
Rendering model states... DONE
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... 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 book.0001_initial... OK
Applying sessions.0001_initial... OK
3. 查看模型的表格,执行migrate之后,在应用的migrations目录下生成创建SQL语句的文件,如下为目录的结构,并查看文件内容,如下:
[root@HappyLau demo]# tree . ├── book │ ├── admin.py │ ├── admin.pyc │ ├── __init__.py │ ├── __init__.pyc │ ├── migrations │ │ ├── 0001_initial.py #新增的创建SQL语句的文件 │ │ ├── 0001_initial.pyc │ │ ├── __init__.py │ │ └── __init__.pyc │ ├── models.py │ ├── models.pyc │ ├── tests.py │ └── views.py ├── demo │ ├── __init__.py │ ├── __init__.pyc │ ├── settings.py │ ├── settings.pyc │ ├── urls.py │ └── wsgi.py └── manage.py 查看 0001_initial.py文件内容,如下: [root@HappyLau demo]# cat book/migrations/0001_initial.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Book', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('book_name', models.CharField(max_length=128)), ('author_name', models.CharField(max_length=128)), ('publish_date', models.DateTimeField()), ], ), migrations.CreateModel( name='Hero', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('hero_name', models.CharField(max_length=128)), ('hero_sex', models.BooleanField()), ('hero_content', models.CharField(max_length=1024)), ('hero_book', models.ForeignKey(to='book.Book')), ], ), ]
通过上面的文件可以发现,通过models类创建数据模型的时候会在数据库中自动生成id字段,该id字段是主键primary_key,且是自增auto_created。如下通过查看数据库的表结构,如下:
MariaDB [book]> show create table book_book ; +-----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +-----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | book_book | CREATE TABLE `book_book` ( `id` int(11) NOT NULL AUTO_INCREMENT, `book_name` varchar(128) NOT NULL, `author_name` varchar(128) NOT NULL, `publish_date` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 | +-----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec) MariaDB [book]> show create table book_hero ;+-----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +-----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | book_hero | CREATE TABLE `book_hero` ( `id` int(11) NOT NULL AUTO_INCREMENT, `hero_name` varchar(128) NOT NULL, `hero_sex` tinyint(1) NOT NULL, `hero_content` varchar(1024) NOT NULL, `hero_book_id` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `book_hero_hero_book_id_766a63d04ebcda8c_fk_book_book_id` (`hero_book_id`), CONSTRAINT `book_hero_hero_book_id_766a63d04ebcda8c_fk_book_book_id` FOREIGN KEY (`hero_book_id`) REFERENCES `book_book` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 | +-----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
4. 使用django shell测试数据模型,django的manage.py提供一个shell工具和数据模型交互的接口,可以实现直接与数据库交互,如下:
[root@HappyLau demo]# python manage.py shell Python 2.7.5 (default, Aug 4 2017, 00:39:18) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) #插入数据(实际执行了INSERT语句) >>> from book.models import Book >>> from book.models import Hero >>> b = Book() >>> b.book_name = "天龙十八部" >>> b.author = "金庸" >>> b.publish_date = "2018-03-17" >>> b.save() >>> b1 = Book() >>> b1.book_name = "射雕英雄传" >>> b1.author = "金庸" >>> b1.publish_date = "2018-03-17" >>> b1.save() 外键数据插入: >>> h = Hero() >>> h.hero_name = "乔峰" >>> h.hero_sex = "男" >>> h.hero_content = "乔峰是一个大英雄,拥有盖世武功,如降龙十八掌,擒龙手等。" >>> h.hero_book = b >>> b.save() >>> h1 = Hero() >>> h1.hero_name = "郭靖" >>> h1.hero_sex = "男" >>> h1.hero_content = "郭靖是个傻大个,但武功高强,肯学,努力!" >>> h1.hero_book = b1 >>> h1.save() 查询数据所有数据(实际执行了SELCT语句): >>> Book.objects.all() [<Book: 天龙十八部>, <Book: 射雕英雄传>] >>> Hero.objects.all() [<Hero: 郭靖>, <Hero: 乔峰>] 根据条件查询数据,如根据主键查询(pk是primary_key) >>> Book.objects.get(pk=1) <Book: 天龙十八部> >>> Book.objects.get(book_name="射雕英雄传") <Book: 射雕英雄传> 更新数据(实际是执行了UPDATE语句): >>> book = Book.objects.get(pk=1) >>> from datetime import datetime >>> book.publish_date datetime.datetime(2018, 3, 17, 0, 0, tzinfo=<UTC>) >>> book.publish_date = datetime(year=1997,month=1,day=1) >>> book.save() /usr/lib64/python2.7/site-packages/django/db/models/fields/__init__.py:1474: RuntimeWarning: DateTimeField Book.publish_date received a naive datetime (1997-01-01 00:00:00) while time zone support is active. RuntimeWarning) >>> book.publish_date datetime.datetime(1997, 1, 1, 0, 0) 删除数据(实际执行了DELETE语句): >>> hero = Hero.objects.get(hero_name='郭靖') >>> hero.delete() >>> Hero.objects.all() [<Hero: 乔峰>] >>> hero.save()
最后查看数据库中的内容:
MariaDB [book]> select * from book_book;
+----+-----------------+-------------+---------------------+
| id | book_name | author_name | publish_date |
+----+-----------------+-------------+---------------------+
| 1 | 天龙十八部 | | 1997-01-01 00:00:00 |
| 2 | 射雕英雄传 | | 2018-03-17 00:00:00 |
+----+-----------------+-------------+---------------------+
2 rows in set (0.00 sec)
MariaDB [book]> select * from book_hero;
+----+-----------+----------+--------------------------------------------------------------------------------------+--------------+
| id | hero_name | hero_sex | hero_content | hero_book_id |
+----+-----------+----------+--------------------------------------------------------------------------------------+--------------+
| 3 | 乔峰 | 1 | 乔峰是一个大英雄,拥有盖世武功,如降龙十八掌,擒龙手等。 | 1 |
| 4 | 郭靖 | 1 | 郭靖是个傻大个,但武功高强,肯学,努力! | 2 |
+----+-----------+----------+--------------------------------------------------------------------------------------+--------------+
2 rows in set (0.00 sec)