day57

ORM query optimization

only to defer the query optimizer

Reduce the pressure on the database

only:

only括号内放Field, the query result is a list of a set of data对象

These field attribute data objects point brackets will no longer query the database,直接就是对象获取属性

也支持点击括号内没有的字段,但是每点击一次就会重新走一次数据库查询

Disadvantages: inefficient

Example:

res = models.Book.objects.only('title')
#print(res)     #拿到对象  数据库语句只走一次
for i in res:
    print(i.title)  #拿到数据所有书名   走一次数据库语句
    print(i.price)  #走5次数据库查询语句,第1次是总体的查询语句,后面4条是4条书籍字段的语句

defer:

Example:

res = models.Book.objects.defer('title')
#print(res)   #打印的结果是列表套对象,走一条数据库语句
for i in res:
    print(i.title) #走5次数据库查询语句,第1次是总体的查询语句,后面4条是4条书籍字段的语句
    print(i.price)  #点price 走一次数据语句 

Summary: only defer to each other with anti relations

What to put in the field defer parentheses check out the object is no such field

If you want to click on each click will once again take the database

And if you click on a field in the non-bracketed will not take the database is operational only object properties

select_related与prefetch_ralated

Example:

res = models.Book.objects.all()
#print(res)    #只走一次数据库语句
for i in res:
print(i.title)  #只走一次数据库语句
print(i.publish)  #正向查询(按字段)    #走5次数据库查询语句,第1次是总体的查询语句,后面4条是4条出版社字段的语句   #多次查询会对数据库造成压力

Example: Using select_related optimization examples

Features:

  1. Select_related only put in parentheses foreign key fields, and the type of the foreign key field is not only one-to-many or many to many
  2. Table internal automatic contingency table associated with the inner and outer brackets will operate with the current key field into an automatic splicing table, then a query data table objects out of the package into one of
  3. Can put a plurality of foreign key fields, separated by commas, sends multiple foreign key table field associated with the current table makes up a large table
  4. Similar to the left join, right join

advantage:

Cross-database table do not go repeating statements, reducing pressure on the database

res = models.Book.objects.select_related('publish')
#print(res)    # 走一条数据库语句
for i in res:
print(i.title)   # 走一条数据库语句
print(i.publish)  # 走一条数据库语句

prefetch_ralated:

Features:

  1. prefetch_ralated internal subquery, will automatically help you step by step query multiple tables, the results of the program are then packaged into an object, or feeling to the user's operating contingency table
  2. Support brackets pass multiple foreign key fields, no restrictions on the type, can be many to many fields, each put a foreign key field, the more take a sql statement on a multi-table query

Example:

res = models.Book.objects.prefetch_related('publish','authors')
#print(res)    # 走两条数据库语句
for i in res:
print(i.title)   # 走两条数据库语句
print(i.publish)  # 走两条数据库语句

the difference:

select_related time: on the contingency table

prefetch_related time: the number of queries on the tables of thousands recommended

MTV and MVC model

MTV: django claimed to be MTV framework, essentially MVC framework

MTV: can be split into

M:models

T:templates

V: views

MVC:

M:models

T:templates

C: controllar route matches

parameter choices

Between the parameter choices, let's take a look at Django ORM create a table field in the class how to create, is not it follows

# 举例这是一张用户基本信息表
class UserInfo(models.Model):
    username = CharField(max_length=32)
    age = IntegerField() # 整型字段不要传max_length参数哦----特别注意
    gender = CharField(max_length=2)# 用户性别

Through the above userinfo table, we can think about whether, in the user's gender field, as if only two human gender representation, male / female, so that, if we have one million user information, and that one million users sex on the coincidence 900,000 are female.

This time, it causes a problem, since the description of our field, only two descriptions will be able to complete this field is described in the user's gender, why we do not want a convenient and concise form to describe what each user's gender?

This time, I do not know whether still remember, there is no data type is only two forms of it? (Boolean value?), Yes that is a Boolean value, you still remember the Boolean value (0: false / 1: True).

This is one way, but in this case, unfortunately we do not need to use the Boolean value in this way, which leads to choices parameters

We still use numbers to describe gender record the user's gender field, we learned to know the database, the information can be stored integer, character why should it? Obviously, because of the small integer character than the space occupied.

Note: Not all of this can be done in just a few descriptive data describing a large number of teams, go with the numbers, but here with the gender field, for example! !

parameter choices concept: it is a kind of pattern lists / tuples, which nested manner with several small minority tuple representing a corresponding relation with

Introduction to Ajax

Ajax namely " A Synchronous J avascript A Nd the X- ML " (Asynchronous JavaScript and XML), refers to a create interactive web pages development technology applications.

Ajax = Asynchronous JavaScript and XML or HTML ( Standard Generalized Markup Language subset).

Ajax is a technique for creating fast dynamic web pages.

Ajax is a without having to reload the entire web page technical section of the page can be updated.

Pros: By exchanging small amounts of data with the server behind the scenes, Ajax can make asynchronous page updates. This means that, for certain parts of the page to be updated without reloading the entire page. (This feature allows users to feel complete the process of requesting a response unknowingly)

XML is a markup language

The grammar scenario

  1. Write configuration file

  2. Can write the front page (odoo framework erp)

    Each company will have its own unique internal company management software, designed to develop internal management software framework odoo

    odoo all internal functions dependent on the implementation framework python2

    Payroll calculation

When we only histology in JQuery encapsulated method does not grasp a native version js use when introduced into jQuery brackets must first remember to manually enter a brace: $ .ajax ({})

ajax basic syntax:

$.ajax({
    url:'',    //数据提交的后端地址,不写就是往当前页面提交,也可以写后缀,全称,跟actions一样
    type:'post', //提交方式  默认是get请求
    data:{'i1':$('#d1').val(),'i2':$('#d2').val()},   //提交的数据
    success:function(data){   //形参data就是异步提交之后后端返回结果
        $('#d3').val(data)    //回调机制需要做的事情
    }
})
一旦你使用了ajax 必知必会三板斧都不再作用于页面  而是与ajax交互
a标签href参数   get请求
form表单        get/post
ajax           get/post

Front and rear ends data encoding format

Front and rear ends of interactive data a different encoding formats for different backend data processing

request.POST
request.FILES
  1. urlencoded
  2. formdat to
  3. application/json
form表单发送数据的编码格式
Content-Type: application/x-www-form-urlencoded
  1. form form default encoding is urlencoded

    urlencoded所对应的数据格式
                        username=jason&password=123
                        django后端针对urlencoded数据 会自动解析并且帮你封装到request.POST中
  2. form form Send files coding Content-Type: multipart / form-data; boundary = ---- WebKitFormBoundaryhjKCHQHDmcE62iMQ

    Formdata format for the data, you can not see the browser's

    django后端只要你的数据满足urlencode格式
    username=jason&password=123
    就会自动帮你解析到request.POST中
    如果你是一个文件对象django后端也会自动识别帮你放到request.FILES中
  3. Forms can not send data form json format you want to pass your only means of ajax

ajax json format data transmission

ajax发送数据的编码格式
ajax能够发送
urlencoded
formdata
application/json
Content-Type: application/x-www-form-urlencoded; charset=UTF-8ajax默认的编码格式也是urlencoded 也就意味着后端django也是将数据解析到request.POST中

When it comes to interaction before and after the end you have to be consistent with the format of the encoded data format

Do not deceive people is a data format of the request header is another format

ajax json data transmission format

dumps        stringify
loads         parse
Content-Type: application/json
{"username":"jason","password":"123"}

django json format for the data backend will not do any processing of data will only how to put request.body intact, the need to deal with their own hands

$('#d1').click(function () {
        $.ajax({
            url:'',
            type:'post',
            contentType:'application/json',  # 1.注意点1
            data:JSON.stringify({'username':'jason','password':'123'}),  # 2.注意点2
            success:function (data) {
                alert(123)
            }
        })
    })

transmission format data file ajax

By means of a built-in objects new

This object can carry both data files also support common key-value pairs

 $('#d1').click(function () {
                // 先生成一个内置对象
                var MyFormData = new FormData();
                //1.先添加普通的键值对
                MyFormData.append('username','json')//添加了一组普通的键值对
                MyFormData.append('password','123');
                //2.添加文件数据
                MyFormData.append('myfile',$('#d2')[0].files[0];)//如何获取input框中文件对象$('#d1')[0].files[0];)
                
$.ajax({
    url:'',
    type:'post',
    data:MyFormData,  # 1
    //发送文件必须要指定的两个参数
    contentType:false//不适用任何编码 MyFormData对象内部自带编码 django后端能够识别 # 2
    procesData:false,//不要处理数据  #3
    success:function(data){
    
    }
    })
})

Serialization

drf  django restframework
        from app01 import models
        from django.core import serializers
        # 序列化目的  将数据整合成一个大字典形式 方便数据的交互
        def zzz(request):
            user_queryset = models.User.objects.all()
            # [{username:...,password:...,hobby:...,},{},{},{}]
            # user_list = []
            # for data in user_queryset:
            #     user_list.append(
            #         {'username':data.username,
            #          'password':data.password,
            #          'gender':data.get_gender_display(),
            #
            #          }
            #     )
            res = serializers.serialize('json',user_queryset)
            return HttpResponse(res)

Circular list

Circular list is another form of memory chain structure. It is characterized by the last table a node pointer field points to the first node , the entire list to form a ring.

(1) chain single cycle - in a single linked list , the terminal node pointer field to point to NULL header or start node to node.

(2) multi-chain circular list - the list of nodes in the plurality of chain rings.

Advantages: from the table starting at any one node can be found in the other node table

Analyzing conditions empty list:

head==head->next;

rear==rear->next;

Tail pointer

With the tail pointer Robin rear of the chain represented by the start node and the terminating node a1 search time is an O (1). TABLE often operate in end to end location of the table, therefore, useful in the use of the tail pointer list represents a single cycle. Robin tail pointer list with lower visible in FIG.

Example: two realized in linear form on the list (a1 ... an) and (b1 ... bn) connected to a linear operation table (a1 ... an, b1 ... bn) of

LinkListConnect(LinkListA,LinkListB)
{//假设A,B为非空循环链表的尾指针
LinkListp=A->next;//①保存A表的头结点位置
A->next=B->next->next;//②B表的开始结点链接到A表尾
free(B->next);//③释放B表的头结点
B->next=p;//④
returnB;//返回新循环链表的尾指针
}

Note: the circular list pointer is not NULL

Note: Due to the circular list is not NULL, it relates to a traversal time, it is determined that the termination condition is no longer p or p-> next is empty as a non-circular list, but is determined whether they are equal to the head pointer

Cycling conditions:

  单链表                  单循环链表
p! = NULL              -> p!= L
p!->next! = NULL       -> p->next! = L

Finally, a node pointer is a pointer to the head

Guess you like

Origin www.cnblogs.com/gfhh/p/11960615.html