Odoo - 获取记录并将其转换为 python 对象

Odoo - Fetch record and cast it into python object

在 Odoo 10-e 中,可以执行查询,然后将结果列表或元组转换为 python 对象。喜欢

 self.env.cr.execute("SELECT * FROM res.users WHERE Id = 1")

在上面的查询中它将return一条记录

self.env.cr.execute("SELECT * FROM res.users")

现在这个查询将 return 一个用户列表。现在有什么方法可以告诉 self.env.cr.fetchall() 我希望结果是单个 User 对象或 List of Users 。如果没有,那么我们可以在获取后转换它们吗?

有一种方法可以在 python 列表对象中获得结果。

    qry = """select id from res_partner where parent_id is Null;"""
    self._cr.execute(qry)
    result = self._cr.dictfetchall() 
    user_ids=[] 
    for ids in result:
        user_ids.append(ids.get('id'))

user_ids变量中,你得到所有res.partner的ID。

您可以通过以下方式获取:

q = "select * from res_users where id = 1"
#q = "select * from res_users"
self.env.cr.execute(q)
res = self.env.cr.dictfetchall()
users = self.env['res.users'].browse([row['id'] for row in res])

使用 dictfetchall() 获取数据,使用 browse() 方法获取用户记录集。

这可能对您有所帮助。

只需将 ORM 层用于那些简单的查询。有一些简单的方法(例如,对于典型的 CRUD-> 创建、读取、更新、删除):

创建 -> 创建(vals)

# creates a user in db and
# returns this user as python object (RecordSet)
created_user = self.env['res.users'].create({'name': 'New User'})

浏览 -> 浏览(list_of_ids)

# reads the whole database rows and
# returns python objects (RecordSet)
browsed_users = self.env['res.users'].browse([1,2])

搜索 -> 搜索(域)

# search database with Odoo's domain syntax
# returns python objects if something were found
domain = [('name', '=', 'New User')]
searched_users = self.env['res.users'].search(domain)

示例仅涉及表面。查看 Odoo's Developer Documentation 了解更多信息。

编辑:使用 ORM 层有优点也有缺点。但是在 Odoo 的上下文中有一个非常大的优势:该层集成了用户访问控制。这只是一大优势。