Django 提供了一个抽象的模型 ("models") 层,
django.db.models.Model
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '127.0.0.1', # 数据库主机
'PORT': 3306, # 数据库端口
'USER': 'root', # 数据库用户名
'PASSWORD': 'abcd123456', # 数据库用户密码
'NAME': 'my_dj_test' # 数据库名字
}
}
from django.db import models
class Musician(models.Model):
first_name = models.CharField(max_length=50) #每个变量对应的是数据库中每个字段
last_name = models.CharField(max_length=50)
instrument = models.CharField(max_length=100)
class Album(models.Model):
artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
release_date = models.DateField()
num_stars = models.IntegerField()
# 因为我现在的Django版本是3.x会出现一些版本不对应的情况,所以我将版本降到了2.1.7 ,没有这个问题的需要此操作
$ pip3 install Django==2.1.7
# Successfully installed Django-2.1.7
# 安装pymysql
$ pip3 install pymysql
# Successfully installed pymysql-0.9.3
import pymysql
pymysql.install_as_MySQLdb()
manage.py makemigrations
,再执行建表的命令manage.py migrate
$ python3 manage.py makemigrations
Migrations for 'signtest':
signtest/migrations/0001_initial.py
- Create model Album
- Create model Musician
- Add field artist to album
$ python3 manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, signtest
Running migrations:
Applying contenttypes.0001_initial... OK
# ...
(venv) pengyapandeMacBook-Air:sangyu pengyapan$
# 卸载mysqlclient
pip install mysqlclient
# 异常:mysqlclient 1.3.13 or newer is required; you have 0.9.3
# 可能是由于Django版本不一致的问题改成,也可以通过修改/Users/lixiang/.env/lib/python3.6/site-packages/django/db/backends/mysql/base.py 这个文件下的注释掉version < (1, 3, 13)
# 这是在sql中执行的命令的,主要是记录建表信息会记录在这个表django_migrations中
DELETE FROM django_migrations WHERE app='your-app-name';
# 下载依赖时增加版本信息
mysql-connector-python==1.0.12
# 要为应用创建初始迁移,请运行makemigrations并指定应用名称。将创建迁移文件夹
./manage.py makemigrations <myapp>