Django链接mysql简单操作

  • settings.py设置
Django settings for djangoTests project.

Generated by 'django-admin startproject' using Django 2.1.1.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 's)-xyea+y^28x$f50qg&su2)6u@@y^02o36d+c2i*@(*-@@xsp'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 'djangoTest1.apps.Djangotest1Config',
    'djangoTest1',  #已经创建好的APP工程名
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',    #需要自己注释掉
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'djangoTests.urls'
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
WSGI_APPLICATION = 'djangoTests.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
#数据库信息
DATABASES = {
   'default': {
       'ENGINE': 'django.db.backends.mysql',
       'NAME': 'test_py',
       'USER': 'tanglong',
       'PASSWORD': 'tanglong',
       'HOST': '172.16.6.100',
       'PORT': 3336,
   }
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'

说明:python3 不在支持MySQLdb

#去项目下修改__init__.py,使其默认数据库模块为pymysql
import pymysql
pymysql.install_as_MySQLdb()
  • 项目下执行
python manage.py makemigrations  #在该APP的migrations目录下生成本地文件0001_initial.py
python manage.py migrate   #同步到数据库
  • 操作models.py

      数据库相关一般都写在这个模块下 ,前提是应用要加到setting中

from django.db import models

# Create your models here.
#新建了一个Student类,继承自models.Model
class Student(models.Model):
    name = models.CharField(max_length=128)
    age = models.IntegerField(max_length=3



#上面代码其实就相当于原生sql

CREATE TABLE myapp_person (
    "id" serial NOT NULL PRIMARY KEY,
    "name" varchar(30) NOT NULL,
    "age" int() NOT NULL
);

#然后进行同步
python manage.py makemigrations
python manage.py migrate

#生成一个
项目名称+下划线+小写类名的表
比如项目叫study_1,那表名就叫study_1_student
#插入数据
class Student(models.Model):
        Student.objects.create(name='lizili',age=18)
        Student.objects.create(name='vic',age=22)
        Student.objects.create(name='zhang',age=12)

#返回数据
    def __str__(self):  #固定格式
        return u'name: %s , age:%s' % (self.name,self.age)
#需要数据的页面
#导入
from study_1.models import Student
#查询,展示
def test(request):
    student_list = Student.objects.all()
    student_str = map(str,student_list)
    return HttpResponse(student_str)
  • 创建新的APP

 在Django项目中可以包含多个APP,相当于一个大型项目中的分系统、子模块、功能部件等,相互之间比较独立,但也有联系,所有APP共享项目资源

#settings.py文件中先不要配置,先执行下面的语句,生成myapp文件夹后再再settings.py文件中配置
python manage.py startapp myapp
  • 创建超级账号
python3.6 manage.py createsuperuser

如图:

这样就可以通过该账号进行登录了

相关推荐
©️2020 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie 返回首页