让我指出这是Django的第2周 - 这意味着我是新手。目标:使用自定义模型从Postges DB检索数据并将此数据返回到视图,然后返回到Django中的模板
settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'opengov_db': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'OGSDB',
'USER': 'web_user',
'PASSWORD': 'admin123',
'HOST': '10.187.240.117',
'PORT': '5432',
}
}
这就是models.py中的内容:
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"
print self.action
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; """)
for row in cursor.fetchall():
print row['estab_name']
return row
最后,这是views.py:
from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.template import RequestContext
def index(request):
# Obtain the context from the HTTP request.
context = RequestContext(request)
return render_to_response('map/index.html', {'title':'Home Page'}, context)
#end index
问题: models.py中的查询将返回一组与业务关联的坐标点和元数据。我想循环遍历它,并返回视图中的数据,以便我可以将其传递给模板文件。需要扩展views.py文件以从models.py中提取数据,但这是如何完成的?
我环顾四周,我知道这不是典型的Django返回数据库对象的方式。但是,必须有一种方法可以将记录集返回到视图而不使用Django教程为您提供的使用SQLite 3.我可以在这里使用一些指导。我没有在网上找到任何描述如何以这种方式做到这一点。这是否意味着你不能?
仅供参考:在浏览器中加载index.html文件时不会返回任何错误。不确定如何验证是否正在检索数据。我确实尝试过: python models.py 这就是返回的内容 -
Traceback (most recent call last):
File "models.py", line 1, in <module>
from django.db import models
File "/usr/local/lib/python2.7/dist-packages/django/db/models/__init__.py", line 5, in <module>
from django.db.models.query import Q
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 17, in <module>
from django.db.models.deletion import Collector
File "/usr/local/lib/python2.7/dist-packages/django/db/models/deletion.py", line 4, in <module>
from django.db.models import signals, sql
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/__init__.py", line 4, in <module>
from django.db.models.sql.subqueries import *
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/subqueries.py", line 12, in <module>
from django.db.models.sql.query import Query
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 22, in <module>
from django.db.models.sql import aggregates as base_aggregates_module
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/aggregates.py", line 9, in <module>
ordinal_aggregate_field = IntegerField()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 116, in __init__
self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 54, in __getattr__
self._setup(name)
File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 47, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
任何协助都会受到欢迎。谢谢。
答案 0 :(得分:1)
这种方法完全没有任何意义。
正如你在其他地方已经被告知的那样,继承model.Field是完全不合适的。字段是模型的一部分,而不是独立的事物,并且不会单独进行SQL查询。如果你真的需要这样做,则继承Model。
但是我不明白你为什么要做任何类的课程。为什么不使用Django ORM?或者如果你坚持通过原始SQL来做,为什么不让getVioPoints
成为一个简单的独立函数,你可以调用它返回数据?由于没有存储状态 - 您的类在实例化时查询数据库并直接返回数据 - 根本没有任何一个类。
(而且您的错误正在发生,因为您需要使用manage.py shell
启动shell,然后导入您的文件。但它仍然无效,您只会收到不同的错误。)