Django模型操作
- 在setting.py中设置数据库连接信息,并注册APP
DATABASES = {
'default':
{
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test_DB',
'HOST': '127.0.0.1',
'PORT': 3306,
'USER': 'root',
'PASSWORD': 'MyNewPass4!',
}
}
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'TestModel1',
]
- 导入pymysql,安装mysql驱动
#__init__.py
import pymysql
pymysql.install_as_MySQLdb()
- 在APP中的models.py创建对应类,这个类必须继承models.Model
from django.db import models
class Test(models.Model):
name = models.CharField(max_length=20)
password = models.CharField(max_length=20)
- 使用manage.py 创建表
通过命令
migrate
makemigrate app_name
migrate app_name
- 修改表
首先修改models.py中的类属性,随后
makemigrate app_name
migrate app_name
- 增删改查
# 通过objects这个模型管理器的all()获得所有数据行,相当于SQL中的SELECT * FROM
list = Test.objects.all()
# filter相当于SQL中的WHERE,可设置条件过滤结果
response2 = Test.objects.filter(id=1)
# save和create创建或者保存
# 获取单个对象
response3 = Test.objects.get(id=1)
# 限制返回的数据 相当于 SQL 中的 OFFSET 0 LIMIT 2;
Test.objects.order_by('name')[0:2]
#数据排序
Test.objects.order_by("id")
# 上面的方法可以连锁使用
Test.objects.filter(name="runoob").order_by("id")
# 输出所有数据
for var in list:
response1 += var.name + " "
views.py与urls.py
#urls.py
from django.urls import path
from . import views, testdb
urlpatterns = [
path('login', views.login),
path('createUser', views.createUser),
path('createGroup', views.createGroup),
path('userSetGroup', views.userSetGroup),
]
urls.py完成请求的转发,调用views.py中的方法来响应请求
from TestModel1 import models
from django.http import HttpResponse
def login(request):
user = models.UserInfo.objects.get(id=1)
return HttpResponse("success" + user.name)
def createUser(request):
models.UserInfo.objects.create(name="tzq", password="961022tzqme".__hash__())
return HttpResponse("success")
def createGroup(request):
models.UserGroup.objects.create(title="admin")
return HttpResponse("success")
def userSetGroup(request):
user = models.UserInfo.objects.get(id=1)
# user.user_group_id = 1
user.__setattr__("user_group_id", 1)
user.save()
return HttpResponse("success")
urls 中的django.urls.path()即表明一个urlpatterns(路由映射),有请求发过来的时候,django遍历urlpatterns直到第一个匹配的。找到匹配的则调用对应的views中的python方法,其中包括HttpRequest实例,即方法中的reques
url中的使用方法,以以下代码为例
from django.urls import path
from . import views
urlpatterns = [
path('articles/2003/', views.special_case_2003),
path('articles/<int:year>/', views.year_archive),
path('articles/<int:year>/<int:month>/', views.month_archive),
path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail),
]
- 不用以/打头
- 使用<>来获取值
- 捕获的值可以选择包括转换器类型。 例如,使用<int:name>捕获整数参数。 如果不包含转换器,则匹配/以外的任何字符串。
Url 匹配示例:
- A request to /articles/2005/03/ would match the third entry in the list. Django would call the function views.month_archive(request, year=2005, month=3).
- /articles/2003/ would match the first pattern in the list, not the second one, because the patterns are tested in order, and the first one is the first test to pass. Feel free to exploit the ordering to insert special cases like this. Here, Django would call the function views.special_case_2003(request)
- /articles/2003 would not match any of these patterns, because each pattern requires that the URL end with a slash.
- /articles/2003/03/building-a-django-site/ would match the final pattern. Django would call the function views.article_detail(request, year=2003, month=3, slug=“building-a-django-site”).
视图
一个视图函数(或简称为视图)是一个 Python 函数,它接受 Web 请求并返回一个 Web 响应。
视图返回一个包含生成的响应的 HttpResponse 对象。每个视图函数都要返回 HttpResponse 对象。
HttpResponse内容
Django中的HttpRequest
Django中的HttpResponse以及JsonResponse