【问题标题】:Django - How to check if django is hitting database for certain queryDjango - 如何检查 django 是否为某些查询访问数据库
【发布时间】:2020-12-07 08:05:29
【问题描述】:

我想优化 django 应用程序,为此我想知道如何检查我的查询是否命中数据库或者我是否从缓存版本中获取结果/返回值?

例如:

products = Products.objects.filter(product_name__icontains="natural")

if not products.exist():
    return Response(...)

total_products = products.count()
first_product = product.first()

我喜欢在 shell 中执行此操作,并想检查哪一行命中数据库,哪一行只是从缓存版本返回结果,以便我可以在我的视图中编写优化查询。

我知道 django-toolbar 但我找不到它是否支持这样的东西(是否某些行命中数据库或结果来自缓存版本)。

问候。

【问题讨论】:

    标签: python django django-rest-framework django-queryset django-debug-toolbar


    【解决方案1】:

    这样检查connection.queries的长度,

    from django.conf import settings
    settings.DEBUG = True
    from django.db import connection
    print(len(connection.queries))
    
    # do something with the database
    products = Products.objects.filter(product_name__icontains="natural")
    print(len(connection.queries))
    
    # and execute the print statement again and again
    total_products = products.count()
    print(len(connection.queries))
    
    
    first_product = product.first()
    print(len(connection.queries))

    参考:

    1. Get SQL query count during a Django shell session

    【讨论】:

      猜你喜欢
      • 2012-03-22
      • 1970-01-01
      • 2021-05-24
      • 2019-03-04
      • 2020-08-27
      • 1970-01-01
      • 2017-12-26
      • 2017-12-17
      • 2018-03-03
      相关资源
      最近更新 更多