Django 07

ORM query optimization

  • It is to reduce the number of database access as possible

only to defer (single table)

  • What passed within only method field, the object will only have to get what property , if the object of obtaining other properties, you can also get, but again access the internal database queries
  • What passed within defer field method, the object does not have to get what property , if the object of acquiring the property, you can get, but again access the internal database queries
  • Anti relationship with each other only defer
# only
book_obj = models.Book.objects.filter(pk=1).only('title').first()
print(book_obj.title)  # 直接获取
print(book_obj.price)  # 需要访问数据库查询

# defer
book_obj = models.Book.objects.filter(pk=1).defer('title').first()
print(book_obj.title)  # 需要访问数据库查询
print(book_obj.price)  # 直接获取

select_related与prefetch_related(跨表)

  • _related: shows that are related to methods and "relationships between tables"
  • Select_related internal table operation is automatically connected, associated with the incoming foreign key field at the table with the current tables stitching together and support one-to-many relationship table, a plurality of support incoming foreign key field
  • Internal prefetch_related is a sub-query, the query multiple tables step by step, to support table-many relationship, support incoming multiple foreign key field, and each additional fields, increase the number of times a query

  • select_related time-consuming methods on the table even when the table is relatively large when the table would be even more time-consuming
  • prefetch_related time-consuming methods on queries

# select_related
# 括号内只能放外键字段, 且外键字段类型是能是一对一或者一对多
# 内部是自动连表操作, 会将括号内外键字段关联的表, 与当前表拼接起来
# 括号内可以放多个外键字段, 用逗号隔开
# 耗时: 连表操作上
book_obj = models.Book.objects.filter(pk=1).select_related('publish').first()
print(book_obj.publish.name)  # 访问一次数据库

book_obj = models.Book.objects.filter(pk=1).select_related().first()
print(book_obj.publish.name)  # 访问两次数据库


# prefetch_related
# 内部是子查询操作, 按步骤查询多个表, 然后将查询的结果封装到对象中
# 括号内可放对个外键字段, 且支持多对多外键
# 每放一个字段, 就会多查询一张表
# 耗时: 查询次数上
book_obj = models.Book.objects.filter(pk=4).prefetch_related('publish', 'authors').first()
print(book_obj.publish.name)
print(book_obj.authors.all())

parameter choices

  • Range for data field is determinable, such as gender, education, etc., having a field of the parameter corresponds to an enumeration enum in MySQL
# User表模型类
class User(models.Model):
    username = models.CharField(max_length=255)
    password = models.CharField(max_length=255)
    
    # 创建数字和学历对应关系的元祖
    edu_level_choices = (
        (1, 'bachelor'),
        (2, 'master'),
        (3, 'doctor'),
        (4, 'others')
    )
    # 将元祖赋值给choices参数, 字段类型为int
    edu_level = models.IntegerField(choices=edu_level_choices)
 
  • Education figures are not a good match, we define normal relations can be stored
+----+----------+----------+-----------+
| id | username | password | edu_level |
+----+----------+----------+-----------+
|  1 | alpha    | 111      |         1 |
|  2 | bravo    | 111      |         2 |
|  3 | charlie  | 111      |         3 |
|  4 | delta    | 111      |         4 |
|  5 | echo     | 111      |         5 |  
+----+----------+----------+-----------+
  • When there is a correspondence relationship, by 对象.get_choices字段_display()obtaining a digital value corresponding to
  • When the correspondence relation does not exist, this method is not given, or returned to the field corresponding to the digital
# 1.存在对应关系时
user_obj1 = models.User.objects.filter(pk=1).first()
print(user_obj1.edu_level)  # 1
print(user_obj1.get_edu_level_display())  # bachelor

# 2.不存在对应关系时
user_obj5 = models.User.objects.filter(pk=5).first()
print(user_obj5.edu_level)  # 5
print(user_obj5.get_edu_level_display())  # 5
  • Not have to use numbers to establish correspondence, you can also use string

MTV and MVC model

  • MTV: models, templates, views
  • MVC: models, views, controller (route matches)

Introduction to Ajax

  • Asyn JavaScript and XML
  • Ajax can not be made without page refresh, implementation, and database interaction
  • Synchronous interaction: After the client sends a request, the server needs to wait for the end of the response, in order to send a second request
  • Asynchronous request: after the client sends a request, the server need not wait for the end of the response, it will be able to send a second request
  • Three essential parameters, a callback function
    • url: address submitted towards the current page is the default submission
    • type: submission, the default is the get request
    • data: Data submitted toward the rear end
    • success function, a function of the parameter data received by the data returned by the backend
# 利用ajax实现页面不刷新的情况下, 现在输入的两个数的和

def ajax(request):
    # 判断当前请求是否ajax请求
    if request.is_ajax():
        # print(request.POST)  # ajax请求发送的数据也在request.POST当中
        v1 = int(request.POST.get('v1'))
        v2 = int(request.POST.get('v2'))
        res = v1 + v2
        return HttpResponse(res)  # 只要有ajax, 三板斧就只返回给ajax的回调函数
    return render(request, 'ajax_page.html')
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax test</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="d1">+<input type="text" id="d2">=<input type="text" id="d3">
<button id="d4">提交</button>
<script>
    $('#d4').on('click', function () {
        // 开启ajax语法句式
        $.ajax({
            url: '',  // 数据提交的后端地址, 不写就是往当前页面提交
            type: 'post',  // 提交方式, 默认还是get请求
            data: {'v1': $('#d1').val(), 'v2': $('#d2').val()},  // 向后端提交的数据
            success: function (data) {  // 形参data是后端返回的结果
                $('#d3').val(data)
            }

        })
    })
</script>
</body>
</html>

Front and rear ends the transmission data encoding format

  • Three data encoding format
    • urlencoded
    • formdat to
    • application/json
  • Send data to the front end of the rear end:

    • a get request tag
    • form form get / post request (urlencoded, form-data)
    • ajax get/post请求 (urlencode, form-data, json)
  • Form to send text form

    • coding: Content-Type: application/x-www-form-urlencoded

    • Data Format: username='bigb'&password='123'

    • For urlencoded backend data, and it will automatically parse the encapsulated request.POST

  • send the form file form (enctype = 'multipart / form-data)
    • Encoding format: Content-Type: multipart/form-data
    • Data Format: 浏览器查看不到
    • Form-data file for the rear end of the data, and resolved automatically saved to the request.FILES
  • Before and after the end of the interaction, they must ensure that the data format consistent with the encoding format

Ajax Json data transmission format

  • ajax default encoding format is: Content-Type: application/x-www-form-urlencodedand thus also encapsulated in request.POST

  • The default is the data transmission ajax urlencoded encoding format, if you want to send json data format, a need to add parameters: contentType: 'application/json'

$('#d1').on('click', function () {
        $.ajax({
            url: '',
            type: 'post',
            // 指定编码方式为: application/json
            contentType: 'application/json',
            data: JSON.stringify({'username': 'bigb', 'password': '123'}),
            success: function (data) {
                alert(123)
            }
        })
    })
  • json format data (binary) will Django rear distal transmitted intact into request.body, note, binary data !!!
def test(request):
    print(request.body)  # b'{"username":"bigb","password":"123"}'
    return render(request, 'test.html')

Ajax data transfer files

  • ajax js file transfer data needs the built-in objects FormDate
  • FormData objects can either pass a file object, you can also pass an ordinary key-value pairs
  • Built-in object files must pass two parameters to specify
    • contentType: false
    • processData: false
def test(request):
    print(request.POST)  # <QueryDict: {'username': ['bigb'], 'password': ['123']}>
    print(request.FILES)  # <MultiValueDict: {'upload_file': [<InMemoryUploadedFile: githublogo.jpg (image/jpeg)>]}
    return render(request, 'test.html')
username:<input type="text" name="username">
password:<input type="password" name="password">
upload_file:<input type="file" name="upload_file" id="d2">
<button id="d1">提交</button>


<script>
    
    $('#d1').on('click', function () {
        // 1.先生成一个内置对象
        let MyFormData = new FormData
        // 2.添加普通键值数据
        MyFormData.append('username', 'bigb')
        MyFormData.append('password', '123')
        // 3.获取并添加文件对象
        MyFormData.append('upload_file', $('#d2')[0].files[0])
        $.ajax({
            url: '',
            type: 'post',
            data: MyFormData,
            // 发送文件必须要指定两个参数
            contentType: false,  // 不使用任何编码, MyFormData内部自带编码
            processData: false,  //不要处理数据
            success: function (data) {
                alert(123)
            }
        })
    })
</script>

Sequencing module

  • The rear end of the data (usually a list of sets of dictionary or dictionaries) to a front end of the sequence, to achieve separation of front and rear ends
  • serialize () method of the object can be serialized queryset
    • The first parameter: 'json'
    • The second argument: queryset objects
from django.core.serializers

# serialize()方法可以序列化queryset对象
def test1(request):
    user_queryset = models.User.objects.all()
    # 第一个参数: 数据格式json, 第二个参数: queryset对象
    res = serializers.serialize('json', user_queryset)
    return HttpResponse(res)


'''
[{"model": "app01.user", "pk": 1, "fields": {"username": "alpha", "password": "111", "edu_level": 1}}, {"model": "app01.user", "pk": 2, "fields": {"username": "bravo", "password": "111", "edu_level": 2}}, {"model": "app01.user", "pk": 3, "fields": {"username": "charlie", "password": "111", "edu_level": 3}}, {"model": "app01.user", "pk": 4, "fields": {"username": "delta", "password": "111", "edu_level": 4}}, {"model": "app01.user", "pk": 5, "fields": {"username": "echo", "password": "111", "edu_level": 5}}]
'''

Guess you like

Origin www.cnblogs.com/bigb/p/11966794.html
07