django(6)

1. Common fields

1.1AutoField int primary key auto_increment

The int auto-increment column must be filled with the parameter primary_key=True. When there is no auto-increment column in the model, a column named id is automatically created.

1.2IntegerField

​ An integer type in the range -2147483648 to 2147483647. (Generally, it is not used to store the mobile phone number (the number of digits is not enough), it is stored directly with a string), the mobile phone number is stored in charfield , but there is no chafield field in django , even if the charField field is written, you write charfield, in the database Look still varcahr! !

​Charfield and varcharfield are up to 255. Textfield is used to store text

Custom char field (written in reference to the source code)
class MyChar(models.Field):
    def __init__(self,max_length,*args,**kwargs):
        self.max_length = max_length
        super().__init__(max_length=max_length,*args,**kwargs)

    def db_type(self, connection):
        return 'char(%s)'%self.max_length

​ max_length must be in the form of keywords, because the source code is so defined.

​ Now, you can define the char field

desc = MyChar(max_length=64,null=True)
1.3DateField

Date field, date format YYYY-MM-DD, equivalent to the datetime.date() instance in Python.

1.4DateTimeField

Datetime field in the format YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ], equivalent to the datetime.datetime() instance in Python.

parameter:

​ auto_now: The time will be updated every time the data is modified

​ auto_now_add: will only be updated once the data is created for the first time

1.5BooleanField(Field)

​ is_delete = BooleanField()

​ When passing a value to this field, you only need to pass a Boolean value (True and False)

​ But corresponding to the database, it stores 0 and 1

1.6TextField(Field)

​ Used to store large pieces of text

​ The database usually cannot store files, because it is too large, so the file path is stored

1.7FileField(Field)

  • String, the path is stored in the database, and the file is uploaded to the specified directory
  • Parameters:
    upload_to = "" The file uploaded by the user will be automatically placed in the file path specified after the equal sign
    storage = None Storage component, default django.core.files.storage.FileSystemStorage

4. Index

**补充外键字段:**

​```python
当你在使用django2.X版本的时候 在建立外键关系时(*****)
需要你手动添加几个关键点参数
models.cascade
db_constraints

Second, database query optimization: only and defer

All statement operations in orm are lazy queries: you will only go to the database when you really need the data, if you only write the orm statement, you will not go to the database. The advantage of this design is to reduce the pressure on the database

2.1.only()

​ values() gets a QuerySet dictionary! ! !

​ Use .all() to get the QuerySet object

res = models.Book.objects.values('title')
print(res)
笔记:values传title,得出的字典K值都是title!
#<QuerySet [{'title': '西游记'}, {'title': '水浒传'}, {'title': '龙王脑海 '}]>

The only thing you get is the object! And value gets a dictionary! Through the point, the value is taken, and the database is no longer accessed

models.Book.objects.only('title')
for r in res:
    print(r.title)  # 只走一次数据库查询
    print(r.price)  # 当你点击一个不是only括号内指定的字段的时候 不会报错 而是会频繁的走数据库查询
#笔记 only得出的结果是QuerySet对象,k为Book,v为only括号内的值
<QuerySet [<Book: 西游记>, <Book: 水浒传>, <Book: 龙王脑海 >]>

2.2defer

The results of only and defer queries are QuerySet objects

res1 = models.Book.objects.defer('title')  # defer与only是相反的
for r in res1:  # defer会将不是括号内的所有的字段信息 全部查询出来封装对象中
    # 一旦你点击了括号内的字段  那么会频繁的走数据库查询
    print(r.title)


#结果
(0.001) SELECT `app01_book`.`id`, `app01_book`.`price`, `app01_book`.`publish_date`, `app01_book`.`kucun`, `app01_book`.`maichu`, `app01_book`.`publish_id` FROM `app01_book`; args=()
(0.001) SELECT `app01_book`.`id`, `app01_book`.`title` FROM `app01_book` WHERE `app01_book`.`id` = 1; args=(1,)
(0.000) SELECT `app01_book`.`id`, `app01_book`.`title` FROM `app01_book` WHERE `app01_book`.`id` = 2; args=(2,)
西游记
水浒传
(0.000) SELECT `app01_book`.`id`, `app01_book`.`title` FROM `app01_book` WHERE `app01_book`.`id` = 4; args=(4,)
龙王脑海 

3.2. The difference between all() and select_related()

1.all() query times are very large

​ all() query efficiency is very low, the system queries once in a loop, and the number of queries is very large

res = models.Book.objects.all()
for r in res:
    print(r.publish.name) # 补充:r.publish.name这是跨表

All tables associated with foreign key fields will be spliced ​​together, and the object point attribute will not go to the database . select_related: It will directly take all the tables associated with the internal and external key fields of the brackets (you can take multiple tables at one time) and splicing it with the current table, thereby reducing the pressure on you to query the database across tables

Note that select_related brackets can only put foreign key fields (one-to-one and one-to-many)
res = models.Book.objects.all().select_related('foreign key field 1__foreign key field 2__foreign key field 3__foreign key field 4'). Now he connects 5 tables together, and it's still a sql statement!

If there are 10 million pieces of data, the .all() method needs to go through the database 10 million times, which puts a lot of pressure on the database.

res = models.Book.objects.all().select_related('publish')
print(res)# <QuerySet [<Book: 龙王脑海 >, <Book: 西游记>, <Book: 水浒传>]>
for r in res:
    print(r.publish.name)
#查询语句:一整条,只走一次数据库
(0.001) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`price`, `app01_book`.`publish_date`, `app01_book`.`kucun`, `app01_book`.`maichu`, `app01_book`.`publish_id`, `app01_publish`.`id`, `app01_publish`.`name`, `app01_publish`.`addr` FROM `app01_book` INNER JOIN `app01_publish` ON (`app01_book`.`publish_id` = `app01_publish`.`id`) LIMIT 21; args=()

3. prefetch_related does not actively connect tables

res = models.Book.objects.prefetch_related('publish')
不主动连表操作(但是内部给你的感觉像是连表操作了)  而是将book表中的publish id全部拿出来  在取publish表中将id对应的所有的数据取出
res = models.Book.objects.prefetch_related('publish')
括号内有几个外键字段 就会走几次数据库查询操作    
for r in res:
    print(r.publish.name)

4. The difference between prefetch_related and select_related:

select_related, connect the table first and then look up, the event is consumed on the connected table, and only goes to the database once.

prefetch_related, if there are several foreign key fields in parentheses, it will take several database query operations

3.3 Transactions

Atomicity: either succeed at the same time or fail at the same time (transfer example)

consistency:

Isolation: do not affect each other

Persistence: The impact is forever

Transactions in orm, very simple

Start a transaction: The code inside the transaction maintains the 4 characteristics of the transaction

from django.db import transaction
with transaction.atomic():
    """数据库操作
       在该代码块中书写的操作 同属于一个事务
    """
print('出了 代码块 事务就结束')

library management system

​ · Mysql is more sensitive to dates than django's own database

1. Replace and connect to the mysql database:

​ 1.settings:databases:{}

​ 2. Two lines of code in init

2. Enter data

3.url plus homepage: from app01 import views

4.views write function

5.html file:

​ staticdirs = 【os.path.join,‘static’】

​ Introduce bootstrcip into static

​ {% load static}

Reprinted in: https://www.cnblogs.com/ZDQ1/p/11565492.html

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326568820&siteId=291194637