Using mysql steps in django framework

Posted by eddieblunt on Wed, 04 Dec 2019 18:24:33 +0100

On the basis of creating django project, explain the use of orm framework

Note: first, create a database manually or by command in mysql, and I will create a database named orm.

1: configure mysql database link string and time zone configuration in settings.py file in project folder

# Registered app
INSTALLED_APPS = [
    'teacher',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

# Configuration database link string
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'crm',
        'USER': 'Database user name',
        'PASSWORD': '******',
        'HOST': '192.168.31.175',
        'PORT': '3306'
    }
}
# Set time zone
TIME_ZONE = 'Asia/Shanghai'

  

 

2: in the project folder, add:

import pymysql
pymysql.install_as_MySQLdb()

 

3: create an entity in the models.py file in the app directory

from django.db import models
# Create your models here.
class Student(models.Model):
    name = models.CharField(max_length=20, verbose_name='Full name')
    age = models.SmallIntegerField(default=18, verbose_name='Age')
    sex = models.SmallIntegerField(default=1, verbose_name='Gender')
    qq = models.CharField(max_length=20, default='', verbose_name='qq')
    phone = models.CharField(max_length=20, default='', verbose_name='Cell-phone number')
    create_time = models.DateTimeField(auto_now_add=True, verbose_name='Creation time')

    def __repr__(self):
        return "student<id=%s,name=%s,age=%s,sex=%s,qq=%s,phone=%s,create_time=%s>" % (
        self.id, self.name, self.age, self.sex, self.qq, self.phone, self.create_time)

  

 

4: enter the django project root directory through the linux system in the pycharm or xshell link development environment, and execute to generate the migration file

  

python manage.py makemigrations teacher

  

4-1: view the sql statement instructions generated by the migration file:

python manage.py sqlmigrate teacher 0001_initial.py

  

 

Then get the generated file through pycharm as follows:

 

5: generate database table

python manage.py migrate

 

View the generated data table through navicat software:

Topics: Python Django Database MySQL