以下是代码:
from django.db import models
import datetime
from django.utils import timezone
class data_model(models.Field):
description = "return and create data objects for visulaizations"
def __init__(self, days, action):
self.days = days
self.action = action
if(self.action == ""):
self.action = "inspections"
getVioPoints(self.action, self.days)
#end init
def getVioPoints(self):
#get points
if(self.action == "violations"):
apendQuery = "where osha_violation_indicator is true"
elif(self.action == "inspections"):
apendQuery = "where osha_violation_indicator is false"
else:
apendQuery = ""
from django.db import connections
conn = connections['opengov_db'].cursor()
conn.execute("""
select distinct a.estab_name, b.latitude, b.longitude, a.site_address, a.site_city, a.site_state, a.site_zip
from osha_inspection a
join latitude_longitude_lookup b on cast(a.activity_nr as text)= b.source_data_id
""",apendQuery,"""
and close_case_date >= now() - interval """,self.days,""" days'
and b.latitude is not null; """)
row = conn.fetchone()
print row
我收到此错误:
Unhandled exception in thread started by <function wrapper at 0x9d9656c>
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 93, in wrapper
fn(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 101, in inner_run
self.validate(display_num_errors=True)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 310, in validate
num_errors = get_validation_errors(s, app)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/validation.py", line 34, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", line 196, in get_app_errors
self._populate()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", line 75, in _populate
self.load_app(app_name, True)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", line 99, in load_app
models = import_module('%s.models' % app_name)
File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", line 40, in import_module
__import__(name)
File "/var/www/opengov/mapPrototypePY/opengov/map/models.py", line 6, in <module>
class data_model(models.Field):
File "/var/www/opengov/mapPrototypePY/opengov/map/models.py", line 39, in data_model
row = conn.fetchone()
NameError: name 'conn' is not defined
我不知道为什么。我知道查询正在运行。但是,这似乎忽略了包含row = conn.fetchone()的conn。我用谷歌搜索过,没有发现任何注意事项。有任何想法吗? 感谢
答案 0 :(得分:2)
如评论中所述,这是一个缩进错误。
你在运行时没有得到实际的IndentationError的原因是因为代码在语法上仍然有效。可能发生的事情是代码在类级别被解释为与方法定义处于同一级别:完全可能拥有该级别的代码,例如设置类级变量和编译器(IndentationError是一个编译器) -time exception)不知道此时conn
不在范围内。