(Day55) Seven, query optimization, MTV and MCV, choices, AJAX, serialization

A, ORM query optimization

(A) only to defer

(1)only

  1. Object field queryset put in parentheses, contains returns a data object, the data object field value contains only
  2. Can also query other fields, but the data source is re-locate to the database, extremely low efficiency
res = models.Book.objects.only('title')

(2)defer

  1. Other field values ​​defer check out the object contains in addition to the field
  2. Can also query other fields, but the data source is a database lookup to get back to the field value
res = models.Book.objects.defer('title')
  1. Only put the foreign key field in brackets, foreign key type can only be one to one, one to many, many to many is not
  2. Database access is not required to go check out the original table and the foreign key table, so the query foreign key tables
  3. When the table when a lot of data, time-consuming
res = models.Book.objects.select_related('publish')
for i in res:
    # print(i.title)
    print(i.publish)
  1. Only put the foreign key field brackets (you can put multiple), will follow the steps query multiple tables, the equivalent of a subquery
  2. Access the database more often, each put a foreign key field, there will be more time database access
res = models.Book.objects.prefetch_related('publish','authors')
for i in res:
    # print(i.title)
    print(i.publish)

Two, MTV and MVC model

  1. MTV is claiming to django framework, in fact, it is the essence of MVC
  2. MTV: The web application into model (Model), the template (Template), view (View) three, in a plug-like, connected together loose coupling between them.
    1. Model (model): Responsible for business objects and database objects (ORM)
    2. Template (template): responsible for how the page displayed to the user
    3. View (View): is responsible for the business logic, and calls the Model and Template at the appropriate time
  3. MVC: the web application into model (Model), controller (Control), view (View) three, in a plug-like, connected together loose coupling between them.
    1. Responsible for the business object model and database objects (ORM)
    2. View is responsible for interaction with the user (page)
    3. Controller (C) accept user input to complete the call model and view the user's request.

Three, choices parameters

  1. .get_字段名_display: Get the corresponding figures worthy of a unified sentence, or can only get digital
  2. It does not correspond to acquire the digital still
# models.py
class User(models.Model):
    username = models.CharField(max_length=64)
    password = models.IntegerField()
    gender_choices = (
        (1,'男'),
        (2,'女'),
        (3,'其他'),
    )
    gender = models.IntegerField(choices=gender_choices)
    
# test.py  
user_obj = models.User.objects.get(pk=1)
user_obj1 = models.User.objects.get(pk=4)

print(user_obj.gender)  # 1
print(user_obj1.gender)  # 4
print(user_obj.get_gender_display())  # 男
print(user_obj1.get_gender_display())  # 4

Four, AJAX

(A) JSON and XML

(1) What is the Json

  1. Refers JSON JavaScript Object Notation (JavaScript Object Notation)
  2. JSON is a lightweight data interchange format text
  3. JSON language independent *
  4. JSON self-descriptive better understood

JSON uses JavaScript syntax to describe data objects, but JSON is still independent of language and platform. JSON parser and JSON library supports many different programming languages.

(2) JSON usage

  • JavaScript
  1. Serialization: JSON.stringify ()
  2. Deserialize: JSON.parse ()
  • Python
    1. Serialization: json.dumps ()
    2. Deserialize: json.loads ()

(3)XML

  1. XML is a markup language, can be applied to write the configuration file and the front page (odoo framework for the development of enterprise management software, depending on python2)
  2. JSON format proposed by Douglas Crockford in 2001, the aim is to replace the cumbersome bulky XML format

(B) What is AJAX

  1. AJAX (Asynchronous Javascript And XML) translated into Chinese is "asynchronous Javascript and XML". That the use of Javascript language to interact with the server asynchronous data transmission for XML (Of course, data transmission is not just XML)
  2. Synchronous interaction: The client sends a request, it must wait for the end of the server response before sending the second request;
  3. Asynchronous interactions: the client sends a request to the server without waiting for the end of the response, it can issue a second request, such as user name check re-registration
  4. AJAX is not a new programming language, but a new method of using the existing standard does not require any browser plug-ins, but requires the user to allow the execution of JavaScript in the browser
  5. Pros: without reloading the entire page, you can exchange data with the server and update part of the page content (asynchronous interaction)

(C) jQuery AJAX to achieve

  1. $ .Ajax ({}): AJAX opening sentence grammar
  2. url: the back-end address of the data submitted, do not write to the current page is submitted, the role and actions of the same
  3. type: Request way, get the default request
  4. data: submit to the back-end data, this time not return HttpResponse object page, but to interact with the data
  5. success: function (data) {}: fixed wording, parameter data for the data returned by the backend
  6. is_ajax (): whether ajax request, it returns a Boolean value
<!--xxx.html-->
<script>
    $('#d4').on('click',function () {
        // 开启ajax语法
        $.ajax({
            url:'',  // 数据提交的后端地址  不写就是往当前页面提交  也可以写后缀 也可以写全称  跟actions一样
            type:'post',  // 提交方式  默认是get请求
            data:{'i1':$('#d1').val(),'i2':$('#d2').val()},  // 提交的数据
            success:function (data) {  // 形参data就是异步提交之后后端返回结果
                $('#d3').val(data)  // 回调机制需要做的事情#
                alert(data)
            }
        })
    })
</script>
# views.py
def xxx(request):
    # print(request.is_ajax())  # 判断当前请求是否是ajax请求
    # print(request.POST)  # ajax发送的post请求 普通的键值对也在request.POST中获取
    if request.is_ajax():
        # i1 = request.POST.get('i1')
        # i2 = request.POST.get('i2')
        # res = int(i1) + int(i2)
        # return HttpResponse(res)  # 给异步回调函数 success
        # return render(request,'xxx.html')  # 给异步回调函数 success
        return redirect('https://www.baidu.com')  # 给异步回调函数 success
    return render(request,'xxx.html')

(D) before and after the transfer of data encoding formats

(1) urlencoded format

  1. The corresponding data format username=wick&password=123, django backend automatically parse and encapsulated in request.POST
  2. ajax form form and the default encoding format

(2) formdata format

  1. For transmitting the file, the browser can not view the data format, automatically identifies and encapsulated in the django request.FILES
  2. ajax form and form can be sent

(3) application / json format

form form can not send the form data, only through ajax

(E) Ajax transport json format data and file data

(1) Data transfer format json

  1. django backend json not process data format, and the need to manually deserialize serialized,
  2. contentType:'application/json',: Set the data type format
  3. data:JSON.stringify({'username':'jason','password':'123'}),: Serialized data
<script>
    // 传json格式的数据
    $('#d1').click(function () {
        $.ajax({
            url:'',
            type:'post',
            contentType:'application/json',
            data:JSON.stringify({'username':'jason','password':'123'}),
            success:function (data) {
                alert(123)
            }
        })
</script>

(2) transfer file data

  1. Generating a built-in objects: var MyFormData = new FormData();The data objects can transfer files, key-value pairs, also supports
  2. append: add a normal key or data file
  3. $('#d1')[0].files[0]: Input box file object
  4. contentType:false,: MyFormData rear end inside the object can be recognized with encode django
  5. processData:false,: No need to process data
<script>
    // 传文件
    $('#d1').click(function () {
        // 先生成一个内置对象
        var MyFormData = new FormData();
        // 1. 先添加普通的键值
        MyFormData.append('username','jason');  // 添加了一组普通的简直对
        MyFormData.append('password','123');
        MyFormData.append('hobby',['read','run']);
        // 2. 添加文件数据
        MyFormData.append('myfile',$('#d2')[0].files[0]);  // 如何获取input框中文件对象$('#d1')[0].files[0]
        $.ajax({
            url:'',
            type:'post',
            data:MyFormData,

            // 发送文件必须要指定的两个参数
            contentType:false,  // MyFormData对象内部自带编码 django后端能够识别
            processData:false,  // 不要处理数据

            success:function (data) {
            }
        })
    })
</script>

(Vi) the sequence of (serializers)

  1. Orm all field values ​​can check out the data object is automatically integrated into a dictionary sent to the client, to facilitate data exchange
  2. Dictionary including table name, primary key, the package dictionary corresponding value field
def ser(request):
    # 1. 拿到用户表里面的所有的用户对象
    user_list=models.User.objects.all()
    # 2. 导入内置序列化模块
    from django.core import serializers
    # 3. 调用该模块下的方法,第一个参数是你想以什么样的方式序列化你的数据
    ret=serializers.serialize('json',user_list)
    return HttpResponse(ret)

Guess you like

Origin www.cnblogs.com/wick2019/p/11967899.html