Python循环数据库行

时间:2013-09-12 10:54:15

标签: python database openerp nonetype

表res_groups_users_rel:

    uid | gid
-----------------
    4      3
    4      12
    4      9

表res_groups:

    id | name           | comment
------------------------------------
     3   Employee         All the Employees 
     9   Contact          Creation of Contact
     12  Manager          This is MyModule

这是我的表格。正如你所看到的,“uid”可以包含几个“gid”,但我只想要评论“MyModule”中的“gid”。我正在尝试以下方法:

def _get_user_group(self, cr, uid, context=None):
actual_id = self.pool.get('res.users').browse(cr, uid, uid).id

query_A = 'SELECT gid FROM res_groups_users_rel WHERE uid = %s'
cr.execute(query_A, (actual_id,))
query_A_results = cr.fetchall()

if query_A_results:
    for gid in query_A_results:

        query_B = 'SELECT name, comment FROM res_groups WHERE id = %s'
        cr.execute(query_B, (gid[0],))
        query_B_results = cr.fetchall()

        if query_B_results:
            for names in query_B_results:
                s = names[1]
                if "MyModule" in s:
                    return names[0]

所以,这个函数应该返回“Manager”,但是它给了我错误:

  

TypeError:“NoneType”类型的参数不可迭代

1 个答案:

答案 0 :(得分:1)

你真的不应该试图通过获得所有结果和迭代来做到这一点。这是一个简单的SQL查询:

cursor.execute('SELECT g.name FROM g.res_groups '
               'JOIN res_groups_users_rel r ON r.gid = g.id '
               'WHERE r.uid = %s AND g.comment LIKE "%%%s%%"',
               (actual_id, "MyModule"))