环境基本步骤
1、可以选择虚拟环境,进入开发环境的虚拟空间,不知道的请看传送门
2、基本包的版本
django@1.11.8
mongoengine@0.15.0
3、安装包
pip install mysqlclient
4、创建一个新的django项目,并指定到虚拟空间的python.exe
一、在django中配置
1、在settings.py中进行数据库配置
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'Test',
'USER':'root',
'PASSWORD':'123456',
'HOST':'localhost',
'PORT':'3306',
}
}
2、新建一个app
python manage.py startapp teachers
3、在设置中添加对其配置类的引用INSTALLED_APPS
INSTALLED_APPS = [
'teachers',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
4、在新建的app的models.py中新建数据模型
from django.db import models
class Teacher(models.Model):
"""用户表"""
name = models.CharField(max_length=20, unique=True, verbose_name=u"教师") # 教师
age = models.BigIntegerField(verbose_name=u"年龄") # 年龄
# user_email = models.EmailField(null=True, blank=True, verbose_name=u"邮箱") # 邮箱
class Meta:
db_table = 'user_info'
verbose_name = '教师表'
verbose_name_plural = "教师表"
def __str__(self):
return self.user_name
5、对模型所做的更改与模型中的模式同步数据库
#运行以创建这些更改的迁移
python manage.py makemigrations
#运行以将这些更改应用于数据库
python manage.py migrate
6、在视图文件中创建一个视图
from django.shortcuts import render, HttpResponse
from .models import TeacherModel
from django.views.generic import View
class Teacher(View):
def get(self, request):
TeacherModel.objects.create(name='Jonder', age=20)
return HttpResponse('hello word')
7、配置url
from django.conf.urls import url
from django.contrib import admin
from teachers.views import Teacher
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^teacher/$', Teacher.as_view(),name='teacher')
]
8、启动开发服务器
python manage.py runserver
二、关于增删改查
1、增加数据
2、查询数据(返回的是一个QuerySet)
class Teacher(View):
def get(self, request):
result = StudentModel.objects.filter(name='Jonder')
print(result[0].age)
return HttpResponse('hello word')
3、修改数据
class Teacher(View):
def get(self, request):
result = StudentModel.objects.filter(name='Jonder').first().update(name='张三')
print(result)
return HttpResponse('hello word')
4、删除数据
class Teacher(View):
def get(self, request):
result = StudentModel.objects.filter(name='张三').first().delete()
print(result)
return HttpResponse('hello word')