目录
一 环境说明
python 3.7
Django 3.0
二 项目目录结构
三 构建项目步骤
第1步:在项目中创建一个model的应用
H:\DjangoTest>django-admin startapp model
第2步:配置settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'chart',
'myfirstvis',
'blog',
# 新增加的应用
'model',
]
# 数据库配置
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 或者使用 mysql.connector.django
'NAME': 'csvt',
'USER':'root',
'PASSWORD':'123456',
'HOST':'localhost',
'PORT':'3306',
}
}
第3步:在models.py中创建模型
from django.db import models
# Create your models here.
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
第4步:数据库表数据生成
H:\DjangoTest>>python manage.py makemigrations model
H:\DjangoTest>>python manage.py migrate model
数据表生成了。
第5步:配置mysite/urls.py
from django.contrib import admin
from django.urls import include,path
from mysite.views import hello
urlpatterns = [
path('admin/', admin.site.urls),
path('hello/', hello),
path('model/', include('model.urls'))
]
第6步:配置model/urls.py
from django.urls import path
from model.views import adddata
from model.views import getdata
from model.views import updatedata
from model.views import deletedata
urlpatterns = [
path('adddata/', adddata),
path('getdata/', getdata),
path('updatedata/', updatedata),
path('deletedata/', deletedata)
]
第7步:修改model/views.py
from __future__ import unicode_literals
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from model.models import Publisher
def adddata(request):
test1 = Publisher(name='google')
test1.save()
return HttpResponse("<p>数据添加成功!</p>")
def getdata(request):
# 初始化
response = ""
response1 = ""
# 通过objects这个模型管理器的all()获得所有数据行,相当于SQL中的SELECT * FROM
list = Publisher.objects.all()
# filter,get相当于SQL中的WHERE,可设置条件过滤结果
list1 = Publisher.objects.filter()
# 获取单个对象
list2 = Publisher.objects.get()
# 限制返回的数据 相当于 SQL 中的 OFFSET 1 LIMIT 2;
list3 = Publisher.objects.order_by('name')[1:2]
# 数据排序
list4 = Publisher.objects.order_by("name")
# 上面的方法可以连锁使用
list5 = Publisher.objects.filter().order_by("id")
# 输出所有数据
for var in list:
response1 += var.name + " "
response = response1
return HttpResponse("<p>" + response + "</p>")
def updatedata(request):
# 修改其中一个id=1的name字段,再save,相当于SQL中的UPDATE
test1 = Publisher.objects.get(name="google")
test1.name = 'baidu'
test1.save()
# 另外一种方式
# Test.objects.filter(id=1).update(name='Google')
# 修改所有的列
# Test.objects.all().update(name='Google')
return HttpResponse("<p>修改成功</p>")
def deletedata(request):
# 删除id=1的数据
#test1 = Test.objects.get(name="baidu")
#test1.delete()
# 另外一种方式
# Test.objects.filter(id=1).delete()
# 删除所有数据
Publisher.objects.all().delete()
return HttpResponse("<p>删除成功</p>")
四 测试
1 增
2 查
3 改
4 删