Odoo 14 CE:如何判断当前用户ID是否在Many2many字段中
Solution for Restricting Document Visibility to Responsible Users in Odoo 14 CE
Your current condition [self.env.user.id,'in','responsible_ids'] is invalid for two key reasons:
- Domain filter tuples follow the format
(field_name, operator, value), but your order is reversed. - You're using the field name string
'responsible_ids'instead of accessing the actual user IDs stored in the field.
Here are the correct approaches to implement this access control:
1. Use Odoo Record Rules (Recommended)
This is the standard way to restrict record visibility in Odoo, as it integrates seamlessly with the built-in access control system.
Via UI (Developer Mode Required)
- Go to Settings > Technical > Security > Record Rules
- Click Create and fill in the details:
- Name: A descriptive label (e.g., "Your Model - Responsible Only Access")
- Model: Select your target document model
- Domain Filter: Enter
[('responsible_ids', 'in', [user.id])] - Groups: Select the user groups this rule applies to (e.g., "Employee" group)
- Permissions: Check the boxes for the permissions you want to restrict (Read, Write, etc.)
- Toggle Active to enable the rule
Via XML Code
Add this record to your module's data XML file to define the rule programmatically:
<record id="rule_your_model_responsible_access" model="ir.rule"> <field name="name">Your Model - Responsible Only Access</field> <field name="model_id" ref="model_your_model_name"/> <!-- Replace with your model's XML ID --> <field name="domain_force">[('responsible_ids', 'in', [user.id])]</field> <field name="groups" eval="[(4, ref('base.group_user'))]"/> <!-- Apply to all internal users --> <field name="perm_read" eval="True"/> <field name="perm_write" eval="True"/> <field name="perm_create" eval="False"/> <field name="perm_unlink" eval="False"/> </record>
2. Method-Level Access Check
If you need to enforce this check in a custom method (e.g., before allowing an action), use this code:
from odoo.exceptions import AccessError # Inside your model method if self.env.user.id not in self.responsible_ids.ids: raise AccessError(_("You are not authorized to view or modify this document."))
3. Domain Filter for Search Queries
When fetching records programmatically, use this domain to filter only accessible records:
accessible_records = self.env['your.model'].search([('responsible_ids', 'in', [self.env.user.id])])
内容的提问来源于stack exchange,提问作者Mestoof
相关产品推荐
相关产品推荐

