Odoo中api.model的model.env含义及model可用的正确导入方式问询
Hey there! Let's tackle your Odoo questions one by one, nice and clear.
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
envto 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.
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:
- First, import the required modules at the top of your Python file:
from odoo import models, api - Define your model class, inheriting from
models.Model: - Decorate your method with
@api.model, and use the first parameter (you can name itmodel,cls, or evenself—thoughclsis standard for class methods) to access the model and itsenvattribute.
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.

