Database Connectivity
- First, make sure we have generated a basic Django project file with the following directory structure:
Reference link for the specific construction process: https://blog.csdn.net/David_house/article/details/131188889?spm=1001.2014.3001.5502 - Find the settings file under the project, open it, and modify the relevant content
- Add the application name (my application name here is app, I added app in the last line)
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app'
]
- Modify the database connection information.
I am using the mysql database here. 'NAME' is followed by the database name you want to use.
DATABASES = {
'default':
{
'ENGINE': 'django.db.backends.mysql',
'NAME': 'dfds',
'HOST':'127.0.0.1',
'PORT':3306,
'USER':'root',
'PASSWORD':'123456'
}
}
- Open the init file in the app directory. Note that it is not the init file in migrations. Add the following content:
import pymysql
pymysql.install_as_MySQLdb()
Table creation
- Open the models.py file and add the information of the tables you want to create. For example, I want to create three tables here. The specific contents are as follows:
# Create your models here.
class Users(models.Model):
#前面的变量名会默认生成为表中的列名,如果想单独设置可以通过属性db_column=''
#当使用CharField时,一定要通过max_length来设置一下最大长度
id=models.AutoField('用户id',primary_key=True) #primary_key为True时表示该列是主键
email=models.CharField('用户邮箱',max_length=50,null=False) #null=False表示不为空
password = models.CharField('用户登录密码',max_length=8,null=False)
class Meta:
db_table='user' #设置对应的表名
class Test(models.Model):
sample_id = models.AutoField('数据唯一标识符', primary_key=True)
classification = models.IntegerField('分类类别', null=False)
features = models.CharField('特征',max_length=1000)
#ForeignKey来指定外键,第一个参数是关联的表,第二个参数是表连接的方式
u_id = models.ForeignKey(Users, on_delete=models.CASCADE)
class Meta:
db_table = 'test'
class getModel(models.Model):
m_id = models.AutoField('模型的唯一标识符', primary_key=True)
model = models.CharField('模型文件保存路径',max_length=1000, null=False)
sample_id = models.ForeignKey(Test,on_delete=models.CASCADE)
class Meta:
db_table = 'model'
- Open the terminal, enter the directory where the manage.py file is located ,
and execute the commandpython manage.py makemigrations
to generate the corresponding model. The execution results are as follows:
3. Execute the command python manage.py migrate
to generate the corresponding data table. The execution results are as follows:
Finally, we went to the database to check and found that the table was automatically generated:
the last three tables were designed by ourselves, and the others are needed when the Django project is running. data sheet