django-ORM相关代码及其sql执行次数

1.普通情况:通过log可以看出,这种情况下,访问了1次数据库

def test(request):
    """测试连表"""
    users = rbac_models.UserInfo.objects.all()
    for user in users:
        print(user.username)
        print(user.password)
        print(user.nickname)
        print(user.email)

    return HttpResponse("OK")

控制台:

2.普通情况:访问外键,可以看出,访问了4次数据库

def test(request):
    """测试连表"""
    users = rbac_models.UserInfo.objects.all()
    for user in users:
        print(user.username)
        print(user.usertype.name)
    return HttpResponse("OK")

 

 

3.使用selected_related,主动连表查询,可以看出,访问了1次数据库

def test(request):
    """测试连表"""
    users = rbac_models.UserInfo.objects.all().select_related("usertype")
    for user in users:
        print(user.username)
        print(user.usertype.name)
    return HttpResponse("OK")

4.连表降低性能,我们可以使用被动连表查询prefetch_related,可以看到访问了数据库2次,查询n个外键字段时,访问n+1次数据库.

def test(request):
    """测试连表"""
    users = rbac_models.UserInfo.objects.all().prefetch_related("usertype")
    for user in users:
        print(user.username)
        print(user.usertype.name)
    return HttpResponse("OK")

 

posted @ 2017-10-09 20:52  jec1999  阅读(355)  评论(0编辑  收藏  举报