如何使外部数据库查询可迭代? [英] How to make an external database query iterable?

查看:150
本文介绍了如何使外部数据库查询可迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:



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 = connection ['cdr']。cursor()
call = cursor.execute('SELECT * FROM cdr')
return render_to_response(cdr_user.html,
{'result' :call},context_instance = RequestContext(request))

cdr_user.html

  {%for result in result%} 

{{res.billsec}}< br />

{%endfor%}

表格如下: p>

  + ------------- + ------------- -  + ------ + ----- + --------------------- + ------- + 
| Field |类型|空|关键|默认|额外|
+ ------------- + -------------- + ------ + ----- + --- ------------------ + ------- +
| 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 | | | |
|频道| varchar(80)| NO | | | |
| dstchannel | varchar(80)| NO | | | |
| lastapp | varchar(80)| NO | | | |
| lastdata | varchar(80)| NO | | | |
|持续时间| int(11)| NO | | 0 | |
| billsec | int(11)| NO | | 0 | |
|处置| 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 | | | |
|序列| varchar(32)| NO | | | |
| peeraccount | varchar(32)| NO | | | |
+ ------------- + -------------- + ------ + ----- + --- ------------------ + ------- +

问题是我得到一个异常值:'long'对象不可迭代

 $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ 
请求方法:GET
请求URL:http:// localhost:8000 / cdr_user /
Django版本:1.4.1
异常类型:TypeError
异常值:
'long'对象不可迭代
异常位置:/usr/local/lib/python2.7 /site-packages/django/template/defaulttags.py在渲染中,第144行
Python可执行文件:/ usr / local / bin / python
Python版本:2.7.0
Python路径:
['/ 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']
服务器时间:Sab,1 Set 2012 19:56 :10 -0300
模板渲染时出错

在模板/home/tectadmin/cdr/billing/config/templates/cdr_user.html中,错误位于第21行
'long'对象不可迭代
11 text-indent:6em;
12}
13< / style>
14 {%extendsindex_cliente.html%}
15 {%load endless%}
16 {%block title%} CDR {%endblock%}
17 {%块内容%}
18
19
20
21 {%for result in result%}
22
23 {{res.billsec}}< ; br />
24
25 {%endfor%}
26
27
28
29
30< br />
31< form name =inputaction =/ user_cdr /method =et>
Traceback切换到复制和粘贴视图

/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py在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))...
▶本地vars

如何使结果迭代显示在我的模板中?
我看到过 https://docs.djangoproject.com/ en / dev / topics / db / sql / 以及其他文档,但我仍然丢失了代码。



谢谢。 >

解决方案

要在Python中迭代SQL查询的结果,请使用 cursor.fetchall()将其转换成列表列表。有一个非常方便的食谱 here 转换这些结果可以轻松访问的对象:

  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)

一旦你有这个课程,这很简单:

 code $ d 
cursor = connections ['cdr']。cursor()
call = cursor.execute('SELECT * FROM cdr')
result = [SQLRow(cursor,r)for cursor.fetchall()]
返回render_to_response(cdr_user.html,
{'result':result},context_instance = RequestContext(request))

这样, billsec 属性(和所有其他属性)仍然可以在您的模板中访问。 p>

I have the following code:

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 %}

The table is like that:

+-------------+--------------+------+-----+---------------------+-------+
| 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   |     |                     |       | 
+-------------+--------------+------+-----+---------------------+-------+

The problem is that I get a "Exception Value: 'long' object is not iterable"

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

How do I make result iterable to show it in my template? I've seen https://docs.djangoproject.com/en/dev/topics/db/sql/ and also other documentation, but I'm still lost in the code.

Thank you.

解决方案

To iterate over the result of a SQL query in Python, use cursor.fetchall() to turn it into a list of lists. There's a very handy recipe here for turning those results into an object you can easily access:

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)

Once you have that class, this is simple:

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))

This way, the billsec attribute (and all other attributes) will still be accessible in your template.

这篇关于如何使外部数据库查询可迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆