Configuration and operation of the database model framework Django

Copyright: Changan white https://blog.csdn.net/weixin_44074810/article/details/90815330

ORM
Table -------> type
field -----> Properties

model

Focus:,

  1. Model configuration
  2. Additions and deletions to the data
    1. 增:book = BookInfo() book.save() 和 BookInfo.objects.create()
    2. 删:book.delete() 和 BookInfo.objects.get().delete()
    3. Change:. Book.name = 'xxx' book.save () and BookInfo.object.get () Update (name = XXX)
      3. Data Query
    4. Underlying query
    5. F object and the object Q
    6. The associated object
    7. Querysets QuerySet

First, project preparation

  1. Create a project
    django-admin startproject bookmanager

  2. Create an application
    Python manager.py startapp Book

  3. Replace the python interpreter: Demand select
    View Path: which python

  4. Add a child application
    to add sub-applications in the INSTALLED_APPS

  5. Localization
    change language, time zone
    # Set Chinese
    LANGUAGE_CODE = 'zh-Hans'
    # Shanghai Asian time zone
    TIME_ZONE = 'Asia / Shanghai'

  6. Template path
    in the application at the same level directory, create templates template folder
    in the TEMPLATES DIRS write your templates path
    [os.path.join (BASE_DIR, 'templates' )],

  7. Project matching urls
    regular: As long as the path admin / even if the match is successful. And the application contains the urls.py
    URL (R & lt '^', the include ( 'book.urls'))

  8. Application of matching urls.py
    create applications urls.py
    regular: path contains booklist /, the view is called a function corresponding bookList
    from django.conf.urls Import URL
    from book.views Import bookList (

urlpatterns = [

# 匹配书籍列表信息的URL,调用对应的bookList视图
url(r'^booklist/$',bookList)

]

  1. Preparation view
    custom view: provides a list of books information
    def bookList (request):

    return HttpResponse(‘OK!’)

10. Turn on the server, the test project
into the project file, open the project corresponding server
Python manage.py the runserver
click the URL to view

Second, configured
to save the connection configuration information in the database in settings.py, Django using default initial configuration database sqlite

1. 使用MySQL数据库首先需要安装驱动程序
pip install PyMySQL

2. 在Django的 工程 同名子目录的  __init__.py  文件中添加如下语句
import pymysql
pymysql.install_as_MySQLdb()

3. 修改DATABASES配置信息
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'HOST': '127.0.0.1',  # 数据库主机
        'PORT': 3306,  # 数据库端口
        'USER': 'root',  # 数据库用户名
        'PASSWORD': 'mysql',  # 数据库用户密码
        'NAME': 'book'  # 数据库名字
    }
}

4. 在MySQL中创建数据库
create database book charset=utf8;

Third, the definition of the model class
model class is defined in the "Application /models.py" file.
Model class must be inherited from the Model class, located in django.db.models package.

Next to the first "book - the characters' management as an example for demonstration.

Definition 1

在models.py 文件中定义模型类。

from django.db import models

# Create your models here.
# 准备书籍列表信息的模型类
class BookInfo(models.Model):
    # 创建字段,字段类型...
    name = models.CharField(max_length=20, verbose_name='名称')
    pub_date = models.DateField(verbose_name='发布日期',null=True)
    readcount = models.IntegerField(default=0, verbose_name='阅读量')
    commentcount = models.IntegerField(default=0, verbose_name='评论量')
    is_delete = models.BooleanField(default=False, verbose_name='逻辑删除')

    class Meta:
        db_table = 'bookinfo'  # 指明数据库表名
        verbose_name = '图书'  # 在admin站点中显示的名称

    def __str__(self):
        """定义每个数据对象的显示信息"""
        return self.name

# 准备人物列表信息的模型类
class PeopleInfo(models.Model):
    GENDER_CHOICES = (
        (0, 'male'),
        (1, 'female')
    )
    name = models.CharField(max_length=20, verbose_name='名称')
    gender = models.SmallIntegerField(choices=GENDER_CHOICES, default=0, verbose_name='性别')
    description = models.CharField(max_length=200, null=True, verbose_name='描述信息')
    book = models.ForeignKey(BookInfo, on_delete=models.CASCADE, verbose_name='图书')  # 外键
    is_delete = models.BooleanField(default=False, verbose_name='逻辑删除')

    class Meta:
        db_table = 'peopleinfo'
        verbose_name = '人物信息'

    def __str__(self):
        return self.name

1) the name of the database table
model class if you do not specify the table name, Django default app application name in lowercase _ lowercase table names called database model class.
You may specify the name of the database table by db_table.

2) on the primary key
primary key column jango will automatically create growth for the table, each model can have only one primary key column,
Django will not create a primary key column after the automatic growth of key columns if you use option to set a property-based.
The primary key column is created default properties for the id, it can be used instead of pk, pk spelling for the primary key.

3) property naming restrictions
can not be reserved keywords python.
Do not allow the use of a continuous underscore, which is determined by the django query.
Defined attribute is specified when the field type, field types specified by the option parameter syntax is as follows:
Property Type field = models (optional)

Charfiled must set max_length

verbose_name main admin background display

4) key
when setting the foreign key, the primary table indicate the need to delete data by on_delete options
for how the foreign key references the table data processing, comprising the optional constants django.db.models

  1. CASCADE Cascade delete the data communication with the foreign key table when the master table data deleted

  2. PROTECT protection, ProtectedError by throwing an exception, the data is deleted to prevent the application of the foreign key primary table

  3. SET_NULL set to NULL, only in this field can be used to allow null = True is null

  4. When SET_DEFAULT set to default values, only if the field has a default value available

  5. The SET () call to a particular value or a particular method

  6. DO_NOTHING do not do anything, if the database cascade of pre-specified, this option will throw an exception IntegrityError

2 Migration

The synchronization model class to the database.

1) migration of files to generate
Python manage.py makemigrations

2) to synchronize database
Python manage.py the migrate

3 Add Data

Adding data in MySQL database

Four, shell tool

shell tools
Django's manage tool provides a shell command, help us configure the current operating environment projects (such as connected databases, etc.),
so that you can perform the test python statements directly in the terminal.

  1. Command to the shell by
    Python manage.py shell

  2. After entering the shell model classes you import keys

例:from book.models import BookInfo,PeopleInfo

Fifth, the operation of the database to add, delete, change

1 increases
to increase the data two ways.

from boook.models import BookInfo

# 方式1 
# 需要手动调用 save() -----> book.save()
book = BookInfo(
    name='python',
    pub_data='2019-06-03'
)
book.save()

# 方式2 直接入库  create -----> 通过模型类.objects.create()保存。
# objects 模型的管理类
# 我们对模型的 增删改查 都找它
BookInfo.objects.create(
    name='java',
    pub_data='2010-06-06'
)

2 Modify
Modify Update There are two ways

from boook.models import BookInfo

# 方式1  ( 手动调用save )

# 1.先查询数据
book = BookInfo.objects.get(id=1)

# 2.直接修改实例的属性
book.readcount=20

# 3. 调用save方法
book.save()



# 方式2  直接更新  ( update )
使用模型类.objects.filter().update(),会返回受影响的行数
# filter
BookInfo.objects.filter(id=1).update(
    readcount = 100,
    commentcount = 200

3 Delete
Delete There are two ways

# 方式1
# 1. 先查询出数据
book = BookInfo.objects.get(id=5)
# 2. 调用删除方法
book.delete()

# 方式2
模型类.objects.filter().delete()

BookInfo.objects.filter(id=6).delete()

Sixth, the operation of the database - Query

Basic conditions query
a basic query

   1. 查询单一结果,如果不存在会抛出模型类.DoesNotExist异常。
    2. all查询多个结果。
    3. count查询结果数量。

# 返回一个数据
book = BookInfo.objects.get(id=1)

# 查询的id 不存在时会抛出异常
book = BookInfo.objects.get(id=100)
try:
    book = BookInfo.objects.get(id=100)
except BookInfo.DoesNotExist:
    pass

# 返回所有结果,是一个列表
BookInfo.objects.all()

# count   返回的是查询到的数量
BookInfo.objects.all().count()
BookInfo.objects.count()

2 filter query
to realize where SQL functions, including

   1. filter过滤出多个结果
    2. exclude排除掉符合条件剩下的结果
    3. get过滤单一结果

对于过滤条件的使用,上述三个方法相同,故仅以filter进行讲解。

过滤条件的表达语法如下:

属性名称__比较运算符=值
# 属性名称和比较运算符间使用两个下划线,所以属性名不能包括多个下划线

BookInfo -----> model class

1)相等
exact:表示判等。
例:查询编号为1的图书。
BookInfo.objects.filter(id__exact=1)
可简写为:
BookInfo.objects.filter(id=1)
--------------------------------------------------------------------------------
# 查询编号为1的图书
# exact 精确的 准确的  就是等于
BookInfo.objects.get(id_exact=1)
BookInfo.objects.get(id=1)  # 相当于是第一个的简写
BookInfo.objects.filter(id=1)  # 返回的是一个列表 想要获得的是一个对象利用下标的形式
# BookInfo.objects.filter(id=1)[0]

2)模糊查询
contains:是否包含。
    说明:如果要包含%无需转义,直接写即可。
例:查询书名包含'传'的图书。
BookInfo.objects.filter(name__contains='传')

startswith、endswith:以指定值开头或结尾。
例:查询书名以'部'结尾的图书
BookInfo.objects.filter(name__endswith='部')

以上运算符都区分大小写,在这些运算符前加上i表示不区分大小写,
如iexact、icontains、istartswith、iendswith.

----------------------------------------------------------------------------
# 查询书名包含'湖'的图书
# contains  包含 的意思
BookInfo.objects.filter(name__contains='湖')


# 查询书名以'部'结尾的图书
# endswith  以什么结尾的意思
BookInfo.objects.filter(name__endswith='部')

3) 空查询
isnull:是否为null。
例:查询书名为空的图书。
BookInfo.objects.filter(name__isnull=True)
4) 范围查询
in:是否包含在范围内。
例:查询编号为1或3或5的图书
BookInfo.objects.filter(id__in=[1,3,5])

5)比较查询
    gt大于 (greater then)
    gte大于等于 (greater then equal)
    lt小于 (less then)
    lte小于等于 (less then equal)

例:查询编号大于3的图书
BookInfo.objects.filter(id__gt=3)

不等于的运算符,使用exclude()过滤器。
例:查询编号不等于3的图书
BookInfo.objects.filter(id__gt=3)
6)日期查询
year、month、day、week_day、hour、minute、second:对日期时间类型的属性进行运算。

例:查询1980年发表的图书。
BookInfo.objects.filter(pub_date__year=1980)

例:查询1990年1月1日后发表的图书。
BookInfo.objects.filter(pub_date__gt='1990-1-1')
  1. F and Q objects
F对象  ----> # 对两个属性的比较 

语法:
filter (字段名__运算符=F('字段名'))

例:查询阅读量大于等于评论量的图书。
from django.db.models import F
BookInfo.objects.filter(readcount__gt=F('commentcount'))

可以在F对象上使用算数运算。
例:查询阅读量大于2倍评论量的图书。
BookInfo.objects.filter(readcount__gt=F('commentcount')*2)

Q objects

多个过滤器逐个调用表示逻辑与关系,同sql语句中where部分的and关键字。

例:需要查询id 大于2 并且阅读量大于20的书籍

# 方式1
# filter().filter()
BookInfo.objects.filter(id__gt=2).filter(readcount__gt=20)

# 方式2
# filter(条件,条件)
BookInfo.objects.filter(id__gt=2,readcount__gt=20)



如果需要实现逻辑或or的查询,需要使用Q()对象结合|运算符,Q对象被义在django.db.models中。
语法如下:
Q(属性名__运算符=值)

例:需要查询id大于2 或者  阅读量大于40的书籍
from django.db.models import Q
BookInfo.objects.filter(Q(id__gt=2)|Q(readcount__gt=40))

Q对象可以使用&、|连接,&表示逻辑与,|表示逻辑或。
Q对象前可以使用~操作符,表示非not。
例:查询编号不等于3的图书。
BookInfo.objects.filter(~Q(id=3))
  1. Aggregate functions and ranking function
1. 聚合函数 

Sum,Max,Min,Avg,Count

聚合函数需要使用   aggregate
语法形式是:aggregate(Xxx('字段'))

# 当前书籍的阅读总量
from django.db.models import Sum,Max,Min,Avg,Count
BookInfo.objects.aggregate(Sum('readcount'))


注意aggregate的返回值是一个字典类型
{'属性名__聚合类小写':值}
如:
{'readcount__sum': 126}

使用count时一般不使用aggregate()过滤器。
例:查询图书总数。
BookInfo.objects.count()
注意count函数的返回值是一个数字。
  1. Sequence
使用order_by对结果进行排序

 默认升序
BookInfo.objects.all().order_by('readcount')
 降序  在order_by()括号中的参数加上 - 就表示降序
BookInfo.objects.all().order_by('-readcount')
  1. Related inquiries
书籍和人物的关系是 一对多
书籍中没有任何关于人物的字段
人物中有关于书籍的字段  book 外键

语法形式:

    通过书籍查询人物信息(已知主表数据,关联查询从表数据)
    主模型(实例对象).关联模型类名小写_set.all()
    
    
    通过人物查询书籍信息(已知 从表数据,关联查询主表数据)
    从表模型(实例对象).外键

Example: Query 1 book character of all information

通过书籍  查询人物

1. 查询书籍
book = BookInfo.objects.get(id=1)
2. 根据书籍关联人物信息
book.perpleinfo_set.all()

Example: to find the people for the book information 1


根据书籍 查询人物

from boook.models import PerpleInfo
1. 查询人物
person = PerpleInfo.objects.get(id=1)
2. 根据人物关联查询书籍
# person.book  实例对象
person.book
person.book.name  # 得到真实的名字
  1. Associated filter query
由多模型类条件查询一模型类数据:

语法如下:

关联模型类名小写__属性名__条件运算符=值

    注意:如果没有"__运算符"部分,表示等于。




语法形式
    需要的是  书籍信息 ,已知条件是  人物信息
    需要的是  主表数据 ,已知条件是  从表信息
    
    filter(关联模型类型小写__字段__运算符=值)
    
    需要的是  人物信息 ,已知条件是  书籍信息
    需要的是  从表信息 ,已知条件是  主表信息
    
    filter(外键__字段__运算符=值)

Example: Query books, books required for the character "Guo Jing"

需要的是图书,条件是人物

1. BookInfo.objects.filter(perpleinfo__name__exact='郭靖')
2. BookInfo.objects.filter(perpleinfo__name='郭靖')

Example: Query books, books required to describe people with "eight"

BookInfo.objects.filter(perpleinfo__description__contains='八')


例:查询书名为“天龙八部”的所有人物
PerpleInfo.objects.filter(book__name='天龙八部')

例:查询图书阅读量大于30的所有人物
PerpleInfo.objects.filter(book__readcount__gt=50)

The query set QuerySet

查询集,也称查询结果集、QuerySet,表示从数据库中获取的对象集合。

当调用如下过滤器方法时,Django会返回查询集(而不是简单的列表):
    1. all():返回所有数据。
    2. filter():返回满足条件的数据。
    3. exclude():返回满足条件之外的数据。
    4. order_by():对结果进行排序。

Two characteristics 2

1)惰性执行 
创建查询集不会访问数据库,直到调用数据时,才会访问数据库,调用数据的情况包括迭代、序列化、与if合用
例如,当执行如下语句时,并未进行数据库查询,只是创建了一个查询集books
	books = BookInfo.objects.all()
继续执行遍历迭代操作后,才真正的进行了数据库的查询
	for book in books:
    	    print(book.name)


2)缓存 
使用同一个查询集,第一次使用时会发生数据库的查询,然后Django会把结果缓存下来,
再次使用这个查询集时会使用缓存的数据,减少了数据库的查询次数。
情况一:如下是两个查询集,无法重用缓存,每次查询都会与数据库进行一次交互,增加了数据库的负载。

from book.models import BookInfo
 [book.id for book in BookInfo.objects.all()]
 [book.id for book in BookInfo.objects.all()]

情况二:经过存储后,可以重用查询集,第二次使用缓存中的数据。

books=BookInfo.objects.all()
[book.id for book in books]
[book.id for book in books]

3 limit the query set

May be removed or slice a standard query set, is equivalent to the limit and offset sql clauses.
Note: does not support negative indexes.

After the return of the query set to slice a new set of queries, the query will not be executed immediately.
If the acquisition of an object, directly [0] is equivalent to [0: 1] .get () , but if there is no data, [0] IndexError exception initiator,
[0:. 1] .get () if no data is abnormal initiator DoesNotExist .

Example: Getting options 1 and 2, running the viewer.
= BookInfo.objects.all Books () [0: 2]
Books

  1. Paging

# Query data
Books BookInfo.objects.all = ()
# paging class introduced
from django.core.paginator Import Paginator
# create a paging instance
the paginator = Paginator (Books, 2)
# specified page data acquired
page_skus = paginator.page (1)
# get paged data
total_page = paginator.num_pages

Guess you like

Origin blog.csdn.net/weixin_44074810/article/details/90815330