Development of WeChat Mini Programs (5) Use of Django Framework Database

Development of WeChat Mini Programs (5) Use of Django Framework Database

Django provides good support for various databases, including: PostgreSQL, MySQL, SQLite, Oracle.
Django provides a unified calling API for these databases. We can choose different databases according to our business needs.
MySQL is the most commonly used database in web applications.
Django ORM
Django model uses its own ORM.
Object Relational Mapping (ORM for short) is used to implement data conversion between different types of systems in object-oriented programming languages.
ORM acts as a bridge between the business logic layer and the database layer.
ORM uses metadata describing the mapping between objects and databases to automatically persist objects in the program to the database.
Insert picture description here

使用 ORM 的好处:
提高开发效率。
不同数据库可以平滑切换。
使用 ORM 的缺点:
ORM 代码转换为 SQL 语句时,需要花费一定的时间,执行效率会有所降低。
长期写 ORM 代码,会降低编写 SQL 语句的能力。
ORM 解析过程:
1、ORM 会将 Python 代码转成为 SQL 语句。
2、SQL 语句通过 pymysql 传送到数据库服务端。
3、在数据库中执行 SQL 语句并将结果返回。

ORM correspondence table:
Insert picture description here
database configuration
Django how to use mysql database to
create a MySQL database (ORM can not operate to the database level, can only operate to the data table) Syntax:

create database 数据库名称 default charset=utf8; # 防止编码问题,指定为 utf8

We create a database named runoob with the encoding specified as utf8:

create database runoob default charset=utf8;  

Open port 3306.
Insert picture description here
Insert picture description here
Insert picture description here
After establishing the database, we find the DATABASES configuration item in the project's settings.py file and modify its information to:

DATABASES = {
    
     
    'default': 
    {
    
     
        'ENGINE': 'django.db.backends.mysql',    # 数据库引擎
        'NAME': 'runoob', # 数据库名称
        'HOST': '127.0.0.1', # 数据库地址,本机 ip 地址 127.0.0.1 
        'PORT': 3306, # 端口 
        'USER': 'root',  # 数据库用户名
        'PASSWORD': 'xulei111', # 数据库密码
    }  
}

Insert picture description here
If you are using the Python2.x version, Chinese comments are added here, so you need to add # --coding: UTF-8--to the head of the HelloWorld/settings.py file .
The above contains the database name and user information, which are the same as the corresponding database and user settings in MySQL. Based on this setting, Django connects with the corresponding database and user in MySQL.
Next, tell Django to use the pymysql module to connect to the mysql database:

# 在与 settings.py 同级目录下的 __init__.py 中引入模块和进行配置
import pymysql
pymysql.install_as_MySQLdb()

Django stipulates that if you want to use a model, you must create an app. We use the following command to create a TestModel app:

django-admin startapp TestModel
目录结构如下:

HelloWorld
|-- HelloWorld
|-- manage.py
...
|-- TestModel
|   |-- __init__.py
|   |-- admin.py
|   |-- models.py
|   |-- tests.py
|   `-- views.py

Insert picture description here
We modify the TestModel/models.py file, the code is as follows:

# models.py
from django.db import models
 
class Test(models.Model):
    name = models.CharField(max_length=20)

Insert picture description here
The above class name represents the database table name and inherits models.Model. The field in the class represents the field (name) in the data table. The data type is CharField (equivalent to varchar), DateField (equivalent to datetime), max_length The parameter limits the length.
Next, find the INSTALLED_APPS item in settings.py, as follows:

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'TestModel',     #这里是要添加的部分
]
$ python manage.py migrate   # 创建表结构
$ python manage.py makemigrations TestModel  # 让 Django 知道我们在我们的模型有一些变更
$ python manage.py migrate TestModel   # 创建表结构

But I got an error in the first step.
Insert picture description here
Try to download the dependency (download whl manually)
Insert picture description here
and install
Insert picture description here
it here. I installed it successfully. If you have any problems, we can solve
Insert picture description here
them together. Then continue to update mysqlclient and
Insert picture description here
find that an error will still be reported, giao!
Then just comment out these two lines of code to
Insert picture description here
run on the command line:

$ python3 manage.py migrate   # 创建表结构
$ python3 manage.py makemigrations TestModel  # 让 Django 知道我们在我们的模型有一些变更
$ python3 manage.py migrate TestModel   # 创建表结构

The structure of the table name is: application name_class name (such as: TestModel_test).
Note: Although we did not set a primary key for the table in models, Django will automatically add an id as the primary key.

Next, we add the testdb.py file in the HelloWorld directory and modify urls.py:

from django.urls import path
 
from . import views,testdb
 
urlpatterns = [
    path('runoob/', views.runoob),
    path('testdb/', testdb.testdb),
]
from django.http import HttpResponse
 
from TestModel.models import Test
 
# 数据库操作
def testdb(request):
    test1 = Test(name='runoob')
    test1.save()
    return HttpResponse("<p>数据添加成功!</p>")

Insert picture description here
Obtaining data
Django provides a variety of ways to obtain the contents of the database, as shown in the following code:

from django.http import HttpResponse
 
from TestModel.models import Test
 
# 数据库操作
def testdb(request):
    # 初始化
    response = ""
    response1 = ""
    
    
    # 通过objects这个模型管理器的all()获得所有数据行,相当于SQL中的SELECT * FROM
    list = Test.objects.all()
        
    # filter相当于SQL中的WHERE,可设置条件过滤结果
    response2 = Test.objects.filter(id=1) 
    
    # 获取单个对象
    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 + " "
    response = response1
    return HttpResponse("<p>" + response + "</p>")

Update data To
modify data, you can use save() or update():

from django.http import HttpResponse
 
from TestModel.models import Test
 
# 数据库操作
def testdb(request):
    # 修改其中一个id=1的name字段,再save,相当于SQL中的UPDATE
    test1 = Test.objects.get(id=1)
    test1.name = 'Google'
    test1.save()
    
    # 另外一种方式
    #Test.objects.filter(id=1).update(name='Google')
    
    # 修改所有的列
    # Test.objects.all().update(name='Google')
    
    return HttpResponse("<p>修改成功</p>")

Deleting data To
delete an object in the database, you only need to call the delete() method of the object:

from django.http import HttpResponse
 
from TestModel.models import Test
 
# 数据库操作
def testdb(request):
    # 删除id=1的数据
    test1 = Test.objects.get(id=1)
    test1.delete()
    
    # 另外一种方式
    # Test.objects.filter(id=1).delete()
    
    # 删除所有数据
    # Test.objects.all().delete()
    
    return HttpResponse("<p>删除成功</p>")

Guess you like

Origin blog.csdn.net/xulei1132562/article/details/113567620