如果我将日志级别设置为 INFO,则以下两行都将导致查询集仍被评估,即使未打印数据:
logger.debug("Count is %s"%Widget.objects.count())
logger.debug("Count is %s", Widget.objects.count())
有没有办法避免这种情况?
我在这里找到了答案:
https://stackoverflow.com/a/4149190/390973
class Lazy(object):
def __init__(self,func):
self.func=func
def __str__(self):
return self.func()
logger.debug(Lazy(lambda: "Count is %s"%Widget.objects.count()))
唯一的方法是将值存储在变量中
obj_count = Widget.objects.count()
logger.debug("Count is %d"% obj_count)
logger.debug("Count is %d", obj_count)