python web后端框架django基于mysql连接数据库、创建数据表、以及关联已有数据表

第一步 :配置mysql数据库连接信息

    找到django项目中setting.py,将DATABASE修改如下(django默认连接的是sqllite数据库,应把其配置信息注释掉):

DATABASES={
    'default':{
        'ENGINE':'django.db.backends.mysql',   # 数据库引擎
        'HOST':'localhost',                    #服务器主机
        'PORT':3306,                           #端口
        'USER':'root',                         #用户root
        'PASSWORD':'123456',                   #密码
        'NAME':'CaiPu'                         #数据库名称
    }
}

第二步:创建项目的app,并为models.py定义表类,该类继承models.Model

     打开终端,进入项目所在目录执行指令:python manage.py startapp [app名称]

执行指令完成后,系统将会自动为项目创建相应的app,在app中找到models.py,对其进行编写分别与数据库中表相对应的类(数据库中不存在的表),例如下:

from django.db import models

# Create your models here.
class test(models.Model):
    # 数据表会自动为表添加id属性,这里无需定义
    title = models.CharField(max_length = 30,default = 'title')
    content = models.TextField(null=True)

第三步:在django同名文件夹(setting和urls所在目录)下找到__init__.py,添加配置如下

from pymysql import install_as_MySQLdb

install_as_MySQLdb()

因为python3之前的版本,使用连接mysql的包是MySQLdb,现在使用的

pyMySQL,为了能正常连接需要转换成MySQLdb,这两行代码就是这个作用

 

第四步:在settin.py文件中找到 INSTALLED_APPS,并为其添加app的名称,例下:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app名称'
]
第五步:生成数据库迁移文件

打开终端,进入项目所在目录,执行l两条指令:

python manage.py makemigrations
python manage.py migrate

至此,mysql数据库中就会出现models中创建的表(对应类)

若要对数据库进行操作,应该在app中views.py中定义路由函数,在路由函数中对使用model数据表进行操作,例如如下,查询查询数据表中所有记录,并将其返回封装到html文件中,并返回至客户前端:

from django.shortcuts import render
from user.models import test
# Create your views here.
# 定义显示用户信息的路由
def userinformation(request):
    # 查询表test的全部数据,返回结果是一个迭代器,需要对其进行迭代才能将数据显示出来
    result = test.objects.all().order_by('id')
    for item in result:
        print(item.id)
        print(item.title)
        print(item.content)

    return render(request,'test.html',{'result':result})

若要自动生成与数据表相对应的类(即model类),打开终端,进入项目所在目录,执行如下语句:

python manage.py inspectdb

执行结果例如下:

(base) mryu@mryu-G3-3590:~/PycharmProjects/CP$ python manage.py inspectdb
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
#   * Rearrange models' order
#   * Make sure each model has one field with primary_key=True
#   * Make sure each ForeignKey has `on_delete` set to the desired behavior.
#   * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
from django.db import models


class AuthGroup(models.Model):
    name = models.CharField(unique=True, max_length=150)

    class Meta:
        managed = False
        db_table = 'auth_group'


class AuthGroupPermissions(models.Model):
    group = models.ForeignKey(AuthGroup, models.DO_NOTHING)
    permission = models.ForeignKey('AuthPermission', models.DO_NOTHING)

    class Meta:
        managed = False
        db_table = 'auth_group_permissions'
        unique_together = (('group', 'permission'),)


class AuthPermission(models.Model):
    name = models.CharField(max_length=255)
    content_type = models.ForeignKey('DjangoContentType', models.DO_NOTHING)
    codename = models.CharField(max_length=100)

    class Meta:
        managed = False
        db_table = 'auth_permission'
        unique_together = (('content_type', 'codename'),)


class AuthUser(models.Model):
    password = models.CharField(max_length=128)
    last_login = models.DateTimeField(blank=True, null=True)
    is_superuser = models.IntegerField()
    username = models.CharField(unique=True, max_length=150)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=150)
    email = models.CharField(max_length=254)
    is_staff = models.IntegerField()
    is_active = models.IntegerField()
    date_joined = models.DateTimeField()

    class Meta:
        managed = False
        db_table = 'auth_user'


class AuthUserGroups(models.Model):
    user = models.ForeignKey(AuthUser, models.DO_NOTHING)
    group = models.ForeignKey(AuthGroup, models.DO_NOTHING)

    class Meta:
        managed = False
        db_table = 'auth_user_groups'
        unique_together = (('user', 'group'),)


class AuthUserUserPermissions(models.Model):
    user = models.ForeignKey(AuthUser, models.DO_NOTHING)
    permission = models.ForeignKey(AuthPermission, models.DO_NOTHING)

    class Meta:
        managed = False
        db_table = 'auth_user_user_permissions'
        unique_together = (('user', 'permission'),)


class DjangoAdminLog(models.Model):
    action_time = models.DateTimeField()
    object_id = models.TextField(blank=True, null=True)
    object_repr = models.CharField(max_length=200)
    action_flag = models.PositiveSmallIntegerField()
    change_message = models.TextField()
    content_type = models.ForeignKey('DjangoContentType', models.DO_NOTHING, blank=True, null=True)
    user = models.ForeignKey(AuthUser, models.DO_NOTHING)

    class Meta:
        managed = False
        db_table = 'django_admin_log'


class DjangoContentType(models.Model):
    app_label = models.CharField(max_length=100)
    model = models.CharField(max_length=100)

    class Meta:
        managed = False
        db_table = 'django_content_type'
        unique_together = (('app_label', 'model'),)


class DjangoMigrations(models.Model):
    app = models.CharField(max_length=255)
    name = models.CharField(max_length=255)
    applied = models.DateTimeField()

    class Meta:
        managed = False
        db_table = 'django_migrations'


class DjangoSession(models.Model):
    session_key = models.CharField(primary_key=True, max_length=40)
    session_data = models.TextField()
    expire_date = models.DateTimeField()

    class Meta:
        managed = False
        db_table = 'django_session'


class User(models.Model):
    user_id = models.SmallIntegerField(primary_key=True)
    username = models.CharField(max_length=20, blank=True, null=True)
    password = models.CharField(max_length=20, blank=True, null=True)
    age = models.CharField(max_length=20, blank=True, null=True)
    imageurl = models.CharField(max_length=30, blank=True, null=True)
    adress = models.CharField(max_length=20, blank=True, null=True)
    telphone = models.CharField(max_length=20, blank=True, null=True)
    create_date = models.CharField(max_length=30, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'user'


class UserTest(models.Model):
    title = models.CharField(max_length=30)
    content = models.TextField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'user_test'

将其复制到app中models.py文件中即可,接下来就可以在views.py文件中对各个数据表进行操作

你可能感兴趣的:(Django)