Improve performance in operation Django ORM

Orm enhance operational performance point of attention

 

Optimization one: try not to check the object, use values ​​is to use values

Direct result of using an object query is 5 sql statement

def youhua(request):
    # 使用对象查
    obj_list = models.Book.objects.all()
    for obj in obj_list:
        print(obj.title,obj.pubs.name)
        
    return render(request,"youhua.html")

Use values ​​query is only executed one sql, will automatically connect table query

def youhua(request):
    # 使用values
    obj_list = models.Book.objects.values('title', 'pubs__name')
    for obj in obj_list:
        print(obj['title'], obj['pubs__name'])

    return render(request,"youhua.html")

Optimization two: select_related ( 'classes')

使用select_related('classes')

Applies to: many-to-one to one query add select_related () method, in brackets is a foreign key field. It will be even table query

def youhua(request):
    # 使用对象查
    obj_list = models.Book.objects.all().select_related('pubs')
    for obj in obj_list:
        print(obj.title, obj.pubs.name)

    return render(request,"youhua.html")

Use prefetch_related (), many to one,

def youhua(request):

    obj_list = models.Book.objects.all().prefetch_related("pubs")
    for obj in obj_list:
        print(obj.title,obj.pubs.name)

    return render(request,"youhua.html")

Use prefetch_related (), many to many,

def youhua(request):

    obj_list = models.Book.objects.all()
    for obj in obj_list:
        print(obj.title,obj.authors.all())

    return render(request,"youhua.html")

def youhua(request):

    obj_list = models.Book.objects.all().prefetch_related("authors")
    for obj in obj_list:
        print(obj.title,obj.authors.all())

    return render(request,"youhua.html")

Optimization of a Four: only () specify the query field

The case of direct queries, will check out all fields

def youhua(request):

    obj_list = models.Book.objects.all()
    for obj in obj_list:
        print(obj.title)

    return render(request,"youhua.html")

Some fields specified query query, use only specified fields will be found that the field we need.

def youhua(request):

    obj_list = models.Book.objects.all().only('title')
    for obj in obj_list:
        print(obj.title)

    return render(request,"youhua.html")

Optimization five: defer () specify the exclusion of certain fields opposite and only query

If the field we need more, no less, can be used to exclude defer

def youhua(request):

    obj_list = models.Book.objects.all().defer('title')
    for obj in obj_list:
        print(obj.pubtime)

    return render(request,"youhua.html")

Note: If you exclude the field, but also check the query will increase the burden, of course, query fields outside the specified field will increase the burden on the query.

Guess you like

Origin www.cnblogs.com/qianniao2122/p/11923431.html