2012-09-01 4 views
5

나는이 다음 코드 :외부 데이터베이스 쿼리를 반복 실행하는 방법은 무엇입니까?

settings.py

DATABASES = { 
    'default': { 
     'ENGINE': 'django.db.backends.mysql', 
     'NAME': 'tectcom',      
     'USER': 'test',      
     'PASSWORD': '***146***',     
     'HOST': '',      
     'PORT': '',      
    }, 

    'cdr': { 
     'ENGINE': 'django.db.backends.mysql', 
     'NAME': 'ast',      
     'USER': '123',      
     'PASSWORD': '654',     
     'HOST': '',      
     'PORT': '',      
    } 

views.py

def cdr_user(request): 
     cursor = connections['cdr'].cursor() 
     calls = cursor.execute('SELECT * FROM cdr') 
     return render_to_response("cdr_user.html", 
       {'result':calls }, context_instance=RequestContext(request)) 

cdr_user.html

{% for res in result %} 

{{ res.billsec }}<br /> 

{% endfor %} 
,691,363 (210)

표는 같다 :

+-------------+--------------+------+-----+---------------------+-------+ 
| Field  | Type   | Null | Key | Default    | Extra | 
+-------------+--------------+------+-----+---------------------+-------+ 
| calldate | datetime  | NO | MUL | 0000-00-00 00:00:00 |  | 
| clid  | varchar(80) | NO |  |      |  | 
| src   | varchar(80) | NO |  |      |  | 
| dst   | varchar(80) | NO | MUL |      |  | 
| dcontext | varchar(80) | NO |  |      |  | 
| channel  | varchar(80) | NO |  |      |  | 
| dstchannel | varchar(80) | NO |  |      |  | 
| lastapp  | varchar(80) | NO |  |      |  | 
| lastdata | varchar(80) | NO |  |      |  | 
| duration | int(11)  | NO |  | 0     |  | 
| billsec  | int(11)  | NO |  | 0     |  | 
| disposition | varchar(45) | NO |  |      |  | 
| amaflags | int(11)  | NO |  | 0     |  | 
| accountcode | varchar(20) | NO | MUL |      |  | 
| userfield | varchar(255) | NO |  |      |  | 
| uniqueid | varchar(32) | NO |  |      |  | 
| linkedid | varchar(32) | NO |  |      |  | 
| sequence | varchar(32) | NO |  |      |  | 
| peeraccount | varchar(32) | NO |  |      |  | 
+-------------+--------------+------+-----+---------------------+-------+ 

문제는 내가 얻을 것입니다 "예외 값 : '긴'개체를 반복 가능하지 않다"

TypeError at /cdr_user/ 
'long' object is not iterable 
Request Method: GET 
Request URL: http://localhost:8000/cdr_user/ 
Django Version: 1.4.1 
Exception Type: TypeError 
Exception Value:  
'long' object is not iterable 
Exception Location: /usr/local/lib/python2.7/site-packages/django/template/defaulttags.py in render, line 144 
Python Executable: /usr/local/bin/python 
Python Version: 2.7.0 
Python Path:  
['/home/tectadmin/cdr/billing', 
'/usr/local/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg', 
'/usr/local/lib/python2.7/site-packages/pip-1.0-py2.7.egg', 
'/usr/local/lib/python2.7/site-packages/django_endless_pagination-1.1-py2.7.egg', 
'/usr/local/lib/python27.zip', 
'/usr/local/lib/python2.7', 
'/usr/local/lib/python2.7/plat-linux2', 
'/usr/local/lib/python2.7/lib-tk', 
'/usr/local/lib/python2.7/lib-old', 
'/usr/local/lib/python2.7/lib-dynload', 
'/usr/local/lib/python2.7/site-packages'] 
Server time: Sab, 1 Set 2012 19:56:10 -0300 
Error during template rendering 

In template /home/tectadmin/cdr/billing/config/templates/cdr_user.html, error at line 21 
'long' object is not iterable 
11 text-indent: 6em; 
12 } 
13 </style> 
14 {% extends "index_cliente.html" %} 
15 {% load endless %} 
16 {% block title %}CDR{% endblock %} 
17 {% block content %} 
18 
19 
20 
21 {% for res in result %} 
22 
23 {{ res.billsec }}<br /> 
24 
25 {% endfor %} 
26 
27 
28 
29 
30 <br /> 
31 <form name="input" action="/user_cdr/" method="et" > 
Traceback Switch to copy-and-paste view 

/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py in get_response 
         response = callback(request, *callback_args, **callback_kwargs) ... 
▶ Local vars 
/home/tectadmin/cdr/billing/config/views.py in cdr_user 
       {'result':result }, context_instance=RequestContext(request)) ... 
▶ Local vars 

나는 결과가 반복 가능한 어떻게해야합니까 그것을 내 템플릿에 표시 하시겠습니까? 나는 https://docs.djangoproject.com/en/dev/topics/db/sql/ 및 기타 문서를 보았지만 코드에서 여전히 분실 상태입니다.

감사합니다.

+0

당신이'예외 값의 전체 역 추적을 게시 할 수 없습니다 : :

당신은 반복 가능 객체해야 결과, 예를 검색 할 .fetchone().fetchmany() 또는 .fetchall()를 호출해야 '긴'개체가 iterable'은 아니다 오류? –

+0

오케이, 나는 모든 Exception을 풀었다. –

+0

Django 응용 프로그램에서 ORM을 사용하지 않고 원시 SQL을 실행하는 이유는 무엇입니까? –

답변

4

파이썬에서 SQL 쿼리 결과를 반복하려면 cursor.fetchall()을 사용하여 목록 목록으로 변환하십시오. 해당 클래스가되면

class SQLRow(object): 
    def __init__(self, cursor, row): 
     for (attr, val) in zip((d[0] for d in cursor.description), row) : 
      setattr(self, attr, val) 

, 이것은 간단하다 :이 쉽게 액세스 할 수있는 객체에 그 결과를 켜기위한 매우 편리한 조리법 here

def cdr_user(request): 
    cursor = connections['cdr'].cursor() 
    calls = cursor.execute('SELECT * FROM cdr') 
    result = [SQLRow(cursor, r) for r in cursor.fetchall()] 
    return render_to_response("cdr_user.html", 
      {'result': result }, context_instance=RequestContext(request)) 

이 방법의 billsec 속성은 (그리고 다른 모든 속성)은 여전히 ​​템플릿에서 액세스 할 수 있습니다.

+0

그것은 완벽하게 작동합니다, 많이 고마워요 !! 전화에 대해 필요한 것이 있으면 알려주세요. –

2

cursor.execute()은 반복 가능을 반환하지 않습니다. 커서 객체를 제 위치에서 수정합니다. 여기에 documentation이 있습니다.

def cdr_user(request): 
    cursor = connections['cdr'].cursor() 
    cursor.execute('SELECT * FROM cdr') 
    calls = cursor.fetchall() 
    return render_to_response("cdr_user.html", 
          {'result':calls }, 
          context_instance=RequestContext(request)) 
+1

템플릿을 가지고 있기 때문에 (res.billsec로 액세스 할 수 없었습니다) 템플릿과 함께 작동하지 않습니다. –

+0

좋은 지적. 나는 그 문제를 안다. 감사! – ecmendenhall

관련 문제