Python Web-Model (Operation)

1. ORM framework ---object relation mapping

Relational Database
When using the ORM framework, there is no need to directly operate database programming
Use ORM framework to use model classes
Model classes and database complete ORM mapping
Use Django model class to complete addition, deletion, modification and query
According to the set class, the corresponding table is automatically generated.
Django has an embedded ORM framework and directly operates the ORM framework .
Steps: Configure setting.py --model.py definition --migration --kernel completes addition, deletion and change to

2. Install mysql and navicat to view videos

3. Modify configuration items

Step 1: Create a project
django-admin startproject chapter01
cd chapter01
python manage.py startapp books
Step 2 : settings.py modification
//第一处
installed apps:{
'books'
}

//第二处
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'demo',
        'HOST':'localhost',
        'PORT': 3306,
        'USER':'root',
        'PASSWORD':'myy040715'
    }
}
Step 3: Install mysql (database settings)
mysql -uroot -p
create database test;
show databases;
Step 4: Install the driver
pip install .\mysqlclient-1.4.6-cp37-cp37m-win_amd64.whl

 Step 5: Run this file
python manage.py runserver

If you get the above error when running the project:

Reason: SSL is enabled by default in higher versions of MySQL.
Solution: Turn off SSL.

The first step: first check the SSL opening status

登录mysql之后,输入该命令:
mysql> SHOW VARIABLES LIKE '%ssl%';

Step 2: Modify the configuration file my.ini

# 路径:C:\ProgramData\MySQL\MySQL Server 8.0
[mysqld]
skip_ssl  # 忽略ssl

Step 3: Restart the mysql service

ctrl+shift+esc按键调出任务管理器—>服务—>找到mysql服务—>右键重新运行

 


Step 4: Re-execute the command:

mysql> SHOW VARIABLES LIKE '%ssl%';

Step 5: Run this file

python manage.py runserver

 Step 6: Make settings in the models .py file
class BookInfo(models.Model):
     name = models.CharField(max_length=20, verbose_name="名称")
     pub_date = models.DateField(verbose_name="发布日期")
     readcount = models.IntegerField(default=0, verbose_name="阅读量")
     commentcount = models.IntegerField(default=0, verbose_name="评论量")
     is_delete = models.BooleanField(default=False, verbose_name="逻辑删除")
def __str__(self):
return self.name
Step 7 : Check settings.py 
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'books',
]
Step 8: Generate migration files 
python manage.py makemigrations

 Step 9: Execute the migration file
python manage.py migrate

4. Create a new class name (ImageInfo)

Step 1: Add a class

Configure the BookInfo and ImageInfo classes in the models.py file in the application, and extract their identical parts into the abstract class (BaseMobel)

from django.db import models

# Create your models here.
class BaseModel(models.Model):
    name = models.CharField(max_length=20,verbose_name="名称")
    pub_date = models.DateField(verbose_name="发布日期")

    class Meta:
        abstract = True #只能当作基类不能当作实例

#继承了上面的属性
class BookInfo (BaseModel):
    readcount = models.IntegerField(default=0,verbose_name="阅读量")
    commentcount = models.IntegerField(default=0,verbose_name="评论量")
    is_delete = models.BooleanField(default=False,verbose_name="逻辑删除")

class ImageInfo(BaseModel):
    likecount = models.IntegerField(default=False, verbose_name="点赞量")

def __str__(self):
    return self.name
Step 2: Generate the migration file and execute the migration file
python manage.py makemigrations
python manage.py migrate
Step 2: View

When viewing in the database (demo), two data tables will appear (books_bookinfo), (books_imageinfo)

5. Database addition, deletion, modification and query

Step one: add database

Enter the database entry port on the console

python manage.py shell

Import the deployment function in the console

from books.models import BookInfo

Add data in the console (the order of the data must be consistent with the order in the database)

1.createadd data
BookInfo.objects.create(name='孙悟空',pub_date='1937-1-2',readcount=100,commentcount=70,is_delete=0

Its data can be viewed in the console (by defining a value)

a=BookInfo.objects.create(name='孙悟空',pub_date='1937-1-2',readcount=100,commentcount=70,is_delete=0)

a.name

a.commentcount

2.save() method adds data

Import the deployment function in the console

from books.models import BookInfo

adding data 

bookinfo=BookInfo(name='Python web',pub_date='1937-01-09',readcount=100,commentcount=70,is_delete=0)

bookinfo.save()
Step 2: Query the database
1.all() method

The all() method queries all records of the model in the database-mapped table. The return value is a QuerySet object, which is a list-like structure. It supports for loops, indexes (negative indexes are not supported), slicing and other operations.

index:
python manage.py shell
//在控制台中导入部署函数
from books.models import BookInfo

all_info=BookInfo.objects.all()
all_info //索引的方法查看所有的数据,返回值是一个QuerySet对象
all_info[0]
all_info[0].name

 

for loop:
python manage.py shell
//在控制台中导入部署函数
from books.models import BookInfo


info_list=[info for info in all_info]
info_list

info_list=[info.name for info in all_info]
info_list//查看的是所有的name

 

2.filter() method

 The filter() method queries the data table according to the query conditions and returns data that meets the conditions. The return value is a QuerySet object.

python manage.py shell
//在控制台中导入部署函数
from books.models import BookInfo

book_info=BookInfo.objects.filter(id=3)
book_info //查看id为3的数据,返回是QuerySet对象

 book_info[0]
 book_info[0].name//查看的是一个值(name)
3.exclude() method 

The exclude() method queries the database according to the query conditions and returns data that does not meet the conditions. The return value is a QuerySet object.

python manage.py shell
//在控制台中导入部署函数
from books.models import BookInfo

ex
ex_info=BookInfo.objects.exclude(id__gte=3)
ex_info

ex_info[0]
ex_info[0].name

 4.get() method

The get() method searches according to the query conditions and returns a record that meets the conditions. The return value is a model object.

python manage.py shell
//在控制台中导入部署函数
from books.models import BookInfo

//get()方法 返回符合条件的一条记录,一个模型
book_obj=BookInfo.objects.get(id=3)
book_obj //返回的一条记录

book_obj.name

5. Get the arranged data order_by() method
 name=BookInfo.objects.order_by('name')
 for i in name:
...     print(i.name)

 6.value accepts optional parameters *fields
all_info=BookInfo.objects.all()
all_info//返回值是一个QuerySet对象。

all_info=BookInfo.objects.values()
all_info//是一个value queryset返回字典

all_info=BookInfo.objects.values_list()
all_info   #字典
7.contains view database
python manage.py shell
//在控制台中导入部署函数
from books.models import BookInfo

res=BookInfo.objects.filter(name__contains='三')      
res
res[0].name

 

Step 3: Delete data
//delete()方法  对象的方法
python manage.py shell
//在控制台中导入部署函数
from books.models import BookInfo

book_obj=BookInfo.objects.get(id=3)
book_obj
book_obj.delete()

Step 4: Modify the database
python manage.py shell
//在控制台中导入部署函数
from books.models import BookInfo

res=BookInfo.objects.filter(id=1).update(is_delete=1)
res

6. Classes defined for multi-table query

Create an application hello

Define the class in models.py in the application

//自定义管理器
from django.db import models

# Create your models here.
class CountryManager(models.Manager):
    def country_name_prefix(self):
        #查询所有结果
        all_countries = self.all()
        for country in all_countries:
            country.country_name = '国家' + country.country_name
            return all_countries
        
class Country(models.Model):
    country_code = models.CharField(max_length=20)
    country_name = models.CharField(max_length=50)

    objects = CountryManager()

    class Meta:
        db_table = 'country'

    def __str__(self):
        return self.country_name

Generate migration files and execute migration files

python manage.py makemigrations
python manage.py migrate

Add data to the database

//在控制台上部署函数
from hello.models import Country
country=Country(country_name='china',country_code='01')
country.save()
country=Country(country_name='us',country_code='02')    
country.save()

1. One-to-many manager

Add a class in the application hello.models.py

class PersonManager(models.Manager):
    def get_queryset(self):
        return super(PersonManager,self).get_queryset().filter(person_nation__exact=1)
    
class Person(models.Model):
    person_name = models.CharField(max_length=20)
    person_age = models.IntegerField(default=0)
    person_money = models.IntegerField(default=0)
    person_nation = models.ForeignKey(Country,on_delete=models.CASCADE,db_column='f')

    objects = PersonManager()
    class Meta:
        db_table = "person"

Generate migration files and execute migration files

python manage.py makemigrations
python manage.py migrate

 

2. One-to-many forward query

The syntax format of forward query in one-to-many relationship is:

                              Current model object.Related fields.Fields to be queried in the associated model

from hello.models import Person

p=Person.objects.get(id=1)
p.person_name

//           当前模型对象.关联字段.关联模型中要查询的字段
country_name=p.person_nation.country_name
country_name

3. One-to-many reverse query

 The syntax format of reverse query in a one-to-many relationship is:

                             Current model object.Associated model table name (lowercase)_set.all()

from hello.models import Country

c=Country.objects.get(id=1)
c

p_country=c.person_set.all()
p_country

//当前模型对象.关联模型表名(小写)_set.all()
p=c.person_set.all()
p//返回值是一个QuerySet
p[0].person_name
p[1].person_name//返回是一个值

4. One-to-one forward query

First add the President class in hello.models

class President(models.Model):
    president_name=models.CharField(max_length=20)
    president_gender=models.CharField(max_length=20)
    president_nation_id = models.OneToOneField(Country,on_delete=models.CASCADE,db_column='f')

    class Meta:
        db_table = "president"

Then generate the migration file and execute the migration file

python manage.py makemigrations
python manage.py migrate

 Then enter the environment in the terminal

python manage.py shell

The forward query method in a one-to-one relationship is the same as the forward query method in a one-to-many relationship. The syntax format is as follows:

                       Current model object.Related fields.Fields to be queried in the associated model 

from hello.models import President

p=President.objects.get(id=1) 
p
//当前模型对象.关联字段.关联模型中要查询的字段
p.president_nation_id.country_name

5. One-to-one reverse query

The syntax format of reverse query in one-to-many-one system (relationship?) is: 

            Current model object. Associated model table name (lowercase). Fields to be queried in the associated model

from hello.models import Country

c=Country.objects.get(id=1)
c
//当前模型对象.关联模型表名(小写).关联模型中要查询的字段
c.president.president_name

7. F and Q objects

 1.F object

The syntax format for using F objects is as follows:

                                                      F (field name)

//首先要引用数据库和F,Q对象
from books.models import BookInfo
from django.db.models import F,Q

BookInfo.objects.filter(readcount__gt=F('commentcount'))
a=BookInfo.objects.filter(readcount__gt=F('commentcount'))
a[0].name
a[1].name
 2.Q object

The syntax format for using Q objects is as follows:

                                     Q(attribute name___operator=value)

#首先要引用数据库和F,Q对象
from books.models import BookInfo
from django.db.models import F,Q

BookInfo.objects.filter(Q(readcount__gt=50),Q(id__lt=3))
BookInfo.objects.filter(Q(readcount__gt=50)|Q(id__lt=3))
BookInfo.objects.filter(~Q(id__lt=3))

3. Aggregation function
#首先导入BookInfo数据库和Avg(平均对象),min(最小值对象)
from books.models import BookInfo
from django.db.models import Avg,Min

BookInfo.objects.aggregate(Avg('readcount'),Min('commentcount')) 
BookInfo.objects.aggregate(avg=Avg('readcount'),min=Min('commentcount'))

8. Execute the original SQL statement

1. Use the Manager.raw() method to execute SQL query statements

The Manager.raw() method receives a raw SQL query statement and returns a RawQuerySet object, which is a query set and supports iterative operations like the QuerySet object. The syntax format of the raw() method is as follows:

           Manager.raw(raw_query, params=None,translations=None)

  • raw_query: represents the original SQL statement.
  • params: Query condition parameters, receiving list or dictionary type data.
  • translations: Represents a field mapping table, which receives dictionary type data that stores the mapping relationship between query fields and model fields. 
//在控制台上导入数据库
from hello.models import Person

p=Person.objects.raw('select * from Person')
p//返回值为一个RawQuerySet

res=[i for i in p]//for循环
res
res[0]
res[1:]


#raw()方法将查询语句中的字段映射至模型字段,因此raw()方法中字段的顺序并不影响查询出的结果。

p=Person.objects.raw('select id.person_name from Person')
p

p=Person.objects.raw('select person_name from Person')
p

It should be noted that Django uses primary keys to distinguish model instances, so the original SQL query statement of the raw() method must contain the primary key, otherwise an invalidQuery exception will be thrown. 

 The raw() method queries data based on field names. The SQL statement in the raw() method can use the as keyword to set aliases for the fields.

#在控制台上导入数据库
from hello.models import Person

res=Person.objects.raw('select id,person_name as p_name from person')
res
res[0]
res[0].person_name
res[0].p_name

This query can also be implemented through the translations parameter of the raw() method.

#在控制台上导入数据库
from hello.models import Person

query_map={"pk":"id","p_age":"person_age","p_name":"person_name"}
p=Person.objects.raw("select * from person",translations=query_map)
res=[i for i in p]
res
res[0]
res[0].person_name 
res[0].pk  

 When querying data, you can use the parameter params in the raw() method to pass query parameters to the original SQL statement. The parameter can be a list or dictionary type data.

#在查询数据时,可以使用raw()方法中参数params为原始SQL语句传递查询参数,该参数可以为一个列表或字典类型的数据。
param=['person_name']
p_name=Person.objects.raw('slect %s from person',param) 
p_name


#使用“%(key)s”作为占位符可以为raw()方法的参数params传递一个字典类型的参数。
param={"id":1} 
p_name=Person.objects.raw('select * from person where id=%(id)s',param)
p_name #返回是一个RawQuerySet对象

 2. The raw() method can also perform additions, deletions, and modifications to the database.
2.1. Add data (insert):
#在控制台上部署函数
from studentinfo.models import Student

student=Student.objects.raw("insert into student(id, sid, name, sex, sclass, grade, academy, major, email, pwd)Values(3, '0003', '小明', '男', '3班', '三年级', '软件与大数据', '区块链技术应用', '[email protected]', '12345')")

student.query._execute_query()

 2.2 Modify the database

student=Student.objects.raw("update student set name=%s where id=1",['葛老师'])
student.query._execute_query()

 

2.3.Delete data
student=Student.objects.raw("delete from student where id=1")                       
student.query._execute_query()
 
3. Use cursor objects to execute SQL statements

 django.db.connection provides a default database connection. Use the connection.cursor() method to obtain the database cursor object, and use the execute() method of the cursor object to execute the original SQL statement.

fetchone() and fetchall() are also common methods of database cursor objects. They return one/all records in the query set respectively.

#在控制台上导入部署函数
from django.db import connection
cursor=connection.cursor()
cursor

cursor.execute('select * from person')#5

#查询全部记录
cursor.fetchall()
#查询一条记录
cursor.fetchone()

Guess you like

Origin blog.csdn.net/2201_76041915/article/details/134582132