一 准备工作

1.1 新建一个项目

root@darren-virtual-machine:~# cd /root/PycharmProjects/

root@darren-virtual-machine:~/PycharmProjects# django-admin startproject orm_demo

root@darren-virtual-machine:~/PycharmProjects# ll

drwxr-xr-x  7 root root 4096 4月   5 20:04 mysite/
drwxr-xr-x  3 root root 4096 4月   6 13:27 orm_demo/
drwxr-xr-x  3 root root 4096 4月   5 16:27 pymysql/

root@darren-virtual-machine:~/PycharmProjects/orm_demo# python3 manage.py startapp app01

root@darren-virtual-machine:~/PycharmProjects/orm_demo# ll

drwxr-xr-x 3 root root 4096 4月   6 13:29 app01/
drwxr-xr-x 3 root root 4096 4月   6 13:28 .idea/
-rwxr-xr-x 1 root root  628 4月   6 13:27 manage.py*
drwxr-xr-x 3 root root 4096 4月   6 13:29 orm_demo/

设置setting.py

root@darren-virtual-machine:~/PycharmProjects/orm_demo# cat orm_demo/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',
]

1.2 创建一个新的数据库

root@darren-virtual-machine:~/PycharmProjects/orm_demo# mysql -uroot -p123456

mysql> create database orm_demo default charset=utf8;
Query OK, 1 row affected (0.01 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| django             |
| mysql              |
| orm_demo           |
| performance_schema |
| sys                |
+--------------------+

配置setting链接数据库

root@darren-virtual-machine:~/PycharmProjects/orm_demo# cat orm_demo/settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'orm_demo',
        'HOST': '127.0.0.1',
        'PORT': 3306,
        'USER': "root",
        'PASSWORD': "123456",
    }
}

导入__init__.py

root@darren-virtual-machine:~/PycharmProjects/orm_demo# cat orm_demo/__init__.py

import pymysql
pymysql.install_as_MySQLdb()

1.3 创建模型

root@darren-virtual-machine:~/PycharmProjects/orm_demo# cat app01/models.py 

from django.db import models

# Create your models here.
class Book(models.Model):
    title = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    pub_date = models.DateField()
    publish = models.ForeignKey("Publish", on_delete=models.CASCADE)
    authors = models.ManyToManyField("Author")


class Publish(models.Model):
    name = models.CharField(max_length=32)
    city = models.CharField(max_length=64)
    email = models.EmailField()


class Author(models.Model):
    name = models.CharField(max_length=32)
    age = models.SmallIntegerField()
    au_detail = models.OneToOneField("AuthorDetail", on_delete=models.CASCADE)


class AuthorDetail(models.Model):
    gender_choices = (
        (0, "女"),
        (1, "男"),
        (2, "保密"),
    )
    gender = models.SmallIntegerField(choices=gender_choices)
    tel = models.CharField(max_length=32)
    addr = models.CharField(max_length=64)
    birthday = models.DateField()

1.4 执行数据库迁移操作

root@darren-virtual-machine:~/PycharmProjects/orm_demo# python3 manage.py makemigrations

Migrations for 'app01':
  app01/migrations/0001_initial.py
    - Create model Author
    - Create model AuthorDetail
    - Create model Publish
    - Create model Book
    - Add field au_detail to author

root@darren-virtual-machine:~/PycharmProjects/orm_demo# cat app01/migrations/0001_initial.py

# Generated by Django 3.0.5 on 2020-04-06 07:10

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Author',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=32)),
                ('age', models.SmallIntegerField()),
            ],
        ),
        migrations.CreateModel(
            name='AuthorDetail',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('gender', models.SmallIntegerField(choices=[(0, '女'), (1, '男'), (2, '保密')])),
                ('tel', models.CharField(max_length=32)),
                ('addr', models.CharField(max_length=64)),
                ('birthday', models.DateField()),
            ],
        ),
        migrations.CreateModel(
            name='Publish',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=32)),
                ('city', models.CharField(max_length=64)),
                ('email', models.EmailField(max_length=254)),
            ],
        ),
        migrations.CreateModel(
            name='Book',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(max_length=32)),
                ('price', models.DecimalField(decimal_places=2, max_digits=5)),
                ('pub_date', models.DateField()),
                ('authors', models.ManyToManyField(to='app01.Author')),
                ('publish', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='app01.Publish')),
            ],
        ),
        migrations.AddField(
            model_name='author',
            name='au_detail',
            field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='app01.AuthorDetail'),
        ),
    ]

root@darren-virtual-machine:~/PycharmProjects/orm_demo# python3 manage.py migrate

Operations to perform:
  Apply all migrations: admin, app01, auth, 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 app01.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 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 sessions.0001_initial... OK

1.5 查看数据库数据

mysql> use orm_demo
mysql> show tables;
+----------------------------+
| Tables_in_orm_demo         |
+----------------------------+
| app01_author               |
| app01_authordetail         |
| app01_book                 |
| app01_book_authors         |
| app01_publish              |
| auth_group                 |
| auth_group_permissions     |
| auth_permission            |
| auth_user                  |
| auth_user_groups           |
| auth_user_user_permissions |
| django_admin_log           |
| django_content_type        |
| django_migrations          |
| django_session             |
+----------------------------+

四个模型,但是创建了五张表,其中自己创建的表的信息如下

mysql> desc app01_book_authors;

+-----------+---------+------+-----+---------+----------------+
| Field     | Type    | Null | Key | Default | Extra          |
+-----------+---------+------+-----+---------+----------------+
| id        | int(11) | NO   | PRI | NULL    | auto_increment |
| book_id   | int(11) | NO   | MUL | NULL    |                |
| author_id | int(11) | NO   | MUL | NULL    |                |
+-----------+---------+------+-----+---------+----------------+

查看数据库表的信息

mysql> desc app01_author
    -> ;
+--------------+-------------+------+-----+---------+----------------+
| Field        | Type        | Null | Key | Default | Extra          |
+--------------+-------------+------+-----+---------+----------------+
| id           | int(11)     | NO   | PRI | NULL    | auto_increment |
| name         | varchar(32) | NO   |     | NULL    |                |
| age          | smallint(6) | NO   |     | NULL    |                |
| au_detail_id | int(11)     | NO   | UNI | NULL    |                |
+--------------+-------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

mysql> desc app01_authordetail
    -> ;
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| id       | int(11)     | NO   | PRI | NULL    | auto_increment |
| gender   | smallint(6) | NO   |     | NULL    |                |
| tel      | varchar(32) | NO   |     | NULL    |                |
| addr     | varchar(64) | NO   |     | NULL    |                |
| birthday | date        | NO   |     | NULL    |                |
+----------+-------------+------+-----+---------+----------------+
5 rows in set (0.01 sec)

mysql> desc app01_book;
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| title      | varchar(32)  | NO   |     | NULL    |                |
| price      | decimal(5,2) | NO   |     | NULL    |                |
| pub_date   | date         | NO   |     | NULL    |                |
| publish_id | int(11)      | NO   | MUL | NULL    |                |
+------------+--------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

mysql> desc app01_book_authors;
+-----------+---------+------+-----+---------+----------------+
| Field     | Type    | Null | Key | Default | Extra          |
+-----------+---------+------+-----+---------+----------------+
| id        | int(11) | NO   | PRI | NULL    | auto_increment |
| book_id   | int(11) | NO   | MUL | NULL    |                |
| author_id | int(11) | NO   | MUL | NULL    |                |
+-----------+---------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

mysql> desc app01_book_publish;
ERROR 1146 (42S02): Table 'orm_demo.app01_book_publish' doesn't exist
mysql> desc app01_book_publish;er
ERROR 1146 (42S02): Table 'orm_demo.app01_book_publish' doesn't exist
    -> ^C

^C
mysql> desc app01_book_publisher;
ERROR 1146 (42S02): Table 'orm_demo.app01_book_publisher' doesn't exist
mysql> desc app01_publisher;
ERROR 1146 (42S02): Table 'orm_demo.app01_publisher' doesn't exist
mysql> desc app01_publish;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| name  | varchar(32)  | NO   |     | NULL    |                |
| city  | varchar(64)  | NO   |     | NULL    |                |
| email | varchar(254) | NO   |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+
table_information

相关文章:

  • 2022-12-23
  • 2021-11-19
  • 2021-05-27
  • 2022-12-23
  • 2022-02-03
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-05-22
  • 2021-06-20
  • 2021-09-23
  • 2022-03-03
  • 2021-09-11
  • 2021-09-17
  • 2022-02-08
相关资源
相似解决方案