You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Odoo中api.model的model.env含义及model可用的正确导入方式问询

Hey there! Let's tackle your Odoo questions one by one, nice and clear.

1. What is model.env in @api.model (per Odoo's official docs)?

In Odoo, model.env (or the env attribute on your model reference) is the environment object—it’s like the backbone carrying all runtime context for your method. Think of it as a container holding everything your method needs to interact with the Odoo system:

  • model.env.user: The currently logged-in user record, so you can check permissions, user groups, or user-specific details.
  • model.env.cr: The database cursor, used for direct SQL queries (though you’ll usually rely on Odoo’s ORM methods instead).
  • model.env.context: A dictionary of context parameters (like active language, current company, or custom flags passed between methods).
  • You can also use env to access other models—for example, model.env['res.partner'].search([('name', '=', 'Acme Corp')]) lets you look up partner records directly from your method.

When you use @api.model, the method gets access to this environment via the model/class reference passed as the first parameter.

2. What do I need to import to use model in an @api.model decorated method?

To get model (or the model class reference) working properly, you just need two key imports, and to structure your method correctly within an Odoo model class:

  1. First, import the required modules at the top of your Python file:
    from odoo import models, api
    
  2. Define your model class, inheriting from models.Model:
  3. Decorate your method with @api.model, and use the first parameter (you can name it model, cls, or even self—though cls is standard for class methods) to access the model and its env attribute.

Here’s a complete concrete example:

from odoo import models, api

class CustomProduct(models.Model):
    _name = 'custom.product'
    _description = 'Custom Product Model'

    @api.model
    def log_current_user(self):
        # Using `self` here (it's the model's empty recordset, but has access to env)
        current_user = self.env.user.name
        print(f"Current user running this method: {current_user}")
        
        # Alternatively, if you name the parameter `model`:
        # @api.model
        # def log_current_user(model):
        #     current_user = model.env.user.name
        #     print(f"Current user running this method: {current_user}")

The most common mistake here is forgetting to inherit from models.Model or missing the api/models imports—double-check those if you’re hitting errors!

内容的提问来源于stack exchange,提问作者M.E.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:50:00